home *** CD-ROM | disk | FTP | other *** search
/ SuperHack / SuperHack CD.bin / CODING / GRAPHICS / ZED3D080.ZIP / ZED3D.ASC < prev    next >
Encoding:
Text File  |  1995-09-26  |  103.7 KB  |  2,647 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
  18.  
  19. Zed3D
  20.  
  21. A compact reference for
  22.  
  23. 3d computer graphics
  24.  
  25.  
  26.  
  27. by Sébastien Loisel
  28.  
  29.  1994, 1995
  30.  
  31. Zed3D - A compact reference for 3d computer graphics
  32.  
  33.  
  34.  
  35. Copyright 1994, 1995 by Sébastien Loisel All Rights Reserved,
  36. version 0.80
  37.  
  38. Welcome to Zed3D the entirely reformatted, entirely re-written,
  39. and hopefully, more useful version of Zed3D. Zed3D is a document
  40. about computer graphics, more particulary real-time 3d graphics.
  41. This document is not meant as a complete reference to 3d
  42. graphics, but rather perhaps as a handy place where you can find
  43. interesting stuff, and also sometimes stuff to supplement your
  44. paperback reference(s). It can also serve as introductory
  45. material for a mathematically able person without experience in
  46. computer graphics. In this case, this document would give the
  47. reader a very solid understanding of the fundamentals of
  48. computer graphics, and some more.
  49.  
  50. The original Zed3D document grew out of my worknotes. As a
  51. matter of fact, the original Zed3D, up to 0.61beta, was my
  52. worknotes. As such, it was messy, incomplete and often
  53. incorrect. I have attempted to correct this a bit now. I still
  54. consider these my worknotes, but I have added more formal
  55. introductory materials which were not in the original document.
  56.  
  57. In this document, I will attempt to describe various aspects of
  58. computer graphics in a clear, useful and complete fashion. You
  59. will find quite a bit of the theoritical aspects, copies of the
  60. calculations and proofs I made and so forth.
  61.  
  62. However, there is the painful fact that I am merely a student,
  63. trying to mark my territory in the university work, and since
  64. this work does not serve that purpose very well, Zed3D will
  65. oftentimes be lacking in areas that I wish I had more time to
  66. document. Also, I will attempt to distribute another nice
  67. portable graphics engine in the future, but that's only if I can
  68. find the time to make it.
  69.  
  70. Also, please note that this document and any accompanying
  71. documentation/software for which I am the author should not be
  72. considered public domain. You can redistribute this whole thing,
  73. unmodified, if no fee is charged for it, otherwise you need the
  74. author's written permission. Also I am not responsible for
  75. anything that might happen anywhere even if it's related
  76. directly or indirectly to this package. If you wish to encourage
  77. my effort, feel free to send me a 10$ check, which will be
  78. considered to be your official registration. If you're really on
  79. a budget, I would appreciate at least a postcard. At any rate,
  80. please read the registration paragraph below. There have been
  81. rumours about a 0.70 version of Zed3D about. This would be a
  82. fake, versions between 0.63 and 0.79 do not exist, and have
  83. never existed.
  84.  
  85. Contact information
  86.  
  87. If you wish to contact me for any reason, you should be using
  88. the following snail-mail address or my e-mail address. Given
  89. that snail-mail addresses tend to be more stable over time, you
  90. might try it if I don't answer to your electronic messages.
  91.  
  92.  
  93.  
  94. E-Mail Address: zed@binkley.cc.mcgill.ca
  95.  
  96.  
  97.  
  98. Snail Mail Address:
  99.  
  100.  
  101.  
  102. For the 1995-1996 school year, I will reside at:
  103.  
  104.  
  105.  
  106. Sébastien Loisel
  107.  
  108. 3436 Aylmer Street, appartment 2
  109.  
  110. Montréal, Québec, Canada
  111.  
  112. Postal Code: H2X 2B6
  113.  
  114.  
  115.  
  116. Otherwise, it is possible to reach me at:
  117.  
  118.  
  119.  
  120. Sébastien Loisel
  121.  
  122. 1 J.K. Laflamme
  123.  
  124. Lévis, Québec, Canada
  125.  
  126. Postal Code G6V 3R1
  127.  
  128. Registration
  129.  
  130. If you want to register your copy of Zed3D for life, and be able
  131. to use the source in any way you want, even commercial (though
  132. commercial utilization of the documentation [this file] still
  133. requires the written permission of the author), you can send me
  134. a cheque of US$10.00. For more information, please consult the
  135. file register.frm, which should have come with this document. If
  136. you are experiencing difficulties with registration or if the
  137. file register.frm is missing, please mail me and we will see if
  138. something can be worked out.
  139.  
  140. Overview
  141.  
  142. I am trying to put a bit more structure into this document. As
  143. such, this is how it is meant to be structured at this moment.
  144.  
  145. The first section is heavily mathematical. It deals with
  146. transformations by and at large. First are discussed linear and
  147. affine transformations, which are used to spin and move stuff in
  148. space in a useful fashion, then is discussed and justified the
  149. perspective transforms. These two sections are very theoritical,
  150. but are required for proper understanding of the later sections.
  151.  
  152. Then there will follow a section dealing specifically with
  153. applications of the preceding theory. Namely, rotation matrices
  154. and their inverse and object hierarchy.
  155.  
  156. The third "section" concerns itself mainly with rendering
  157. techniques. These are becoming less and less important for
  158. several reasons. The complexity of the problem is of course not
  159. in the rendering section of the pipeline. Second, the recent
  160. trend has pushed the rendering part of the pipeline into cheap
  161. video hardware which can do the job fast and effectively while
  162. the CPU is off to some other, more important task. Eventually,
  163. we can hope that transforming objects will also be made a part
  164. of popular low-cost hardware, but that remains to be seen. As it
  165. is now, this is often the job of either the CPU, or sometimes we
  166. might wish to give this job to a better co-processor (for
  167. example, a programmable DSP).
  168.  
  169. Fourthly, an attempt will be made to describe a few shading
  170. models and visible surface determination techniques. Shading
  171. models are but loosely related to the way the polygons are
  172. drawn. Visible surface determination depends somewhat more on
  173. the way polygons are drawn, and is often implemented in hardware.
  174.  
  175. The following section deals with a few of the computer graphics
  176. related problems that are often encountered, such as error
  177. tolerant normal computation, the problem of finding a correctly
  178. oriented normal and polygon triangulation.
  179.  
  180. Of course, a lot of topics remain to be covered, such as
  181. real-time collision detection, quaternions and SLERP for
  182. rotation interpolation and keyframe animations, octrees and
  183. other data structures. However, I unfortunately do not have the
  184. time to write all of that down for the general public.
  185.  
  186. Vector mathematics
  187.  
  188. Introduction
  189.  
  190. Linear algebra is a rather broad yet basic field of college
  191. level mathematics. It is being taught (or should be at any rate)
  192. early on to students in mathematics and engineering. However
  193. simple it is, it's a lengthy (and somewhat boring, in my humble
  194. opinion) topic to discuss. And since this document is not meant
  195. as a mathematics textbook, I will only give here the gist of the
  196. thing.
  197.  
  198. If you need further information on the topic, browse your local
  199. library for linear algebra books and somesuch, or go ask a
  200. professor. As of now, I'm not making any bibliography for this,
  201. but if and when I do, I'll try to give a few decent references.
  202.  
  203. The purpose of linear algebra in 3d graphics is to implement all
  204. the rotation, skewing, translation, changes in coordinates, and
  205. otherwise affine transformations to 3d object. The applications
  206. range from merely rotating an object about it's own system of
  207. axis to object hierarchy, moving cameras and can be extended
  208. through quaternions for rotation interpolation and such.
  209.  
  210. As such, linear algebra is something that is essential to the
  211. usefulness of a 3d graphics engine.
  212.  
  213. Since my prime concern is 3d graphics, I will give only whatever
  214. theory is absolutely necessary to 3d mathematics. What's below
  215. extends in a vary natural way to n dimensions, n>3, except for
  216. cross product, which is a bit awkward.
  217.  
  218. Vector operations
  219.  
  220. A vector in 3d is noted (a,b,c) where a, b and c are real
  221. numbers. Similarly, a vector in 2d is noted (a,b) for a, b real
  222. numbers. The vector for which all components are null deserves a
  223. special mention, it is usually noted 0, with the proper number
  224. of components implied in the notation but not explicitly given.
  225.  
  226. Vector addition is defined as follow. Let U=(u1,u2,u3) and
  227. V=(v1,v2,v3) then the notation U+V means (u1+v1,u2+v2,u3+v3).
  228. Similarly, for 2d vectors, (u1,u2)+(v1,v2) means (u1+v1,u2+v2).
  229.  
  230. Multiplication of a vector by a scalar is defined as follow.
  231. Given vector U and a scalar a (a is a real number), then a*U
  232. means (a*u1,a*u2,a*u3).
  233.  
  234. Multiplication by the scalar -1 has a special notation. -1*U is
  235. written simply -U.
  236.  
  237. Vector difference is a theorem from the above. U-V can be
  238. rewritten U+-1*V, which is a simple addition and a
  239. multiplication by the scalar -1 as above.
  240.  
  241. Multiplication of two vectors has no intuitive meaning. However,
  242. two types of "multiplications" of vectors are usually defined,
  243. which have little or no relation to the usual real number
  244. multiplication.
  245.  
  246. The first is dot product. U dot V (usually noted UV) yields a
  247. real number (not a vector). (u1,u2,u3)(v1,v2,v3) means
  248. u1*v1+u2*v2+u3*v3. Similarly for 2d vectors,
  249. (u1,u2)(v1,v2)u1*v1+u2*v2.
  250.  
  251. Vectors have a length, defined as follow. The lentgh (or module,
  252. or norm) of vector U is written |U| and has the value of
  253. (UU)1/2. If the length of a vector is one, the vector is said to
  254. be of unit length, or a unit or normal vector.
  255.  
  256. Dot product is also used to define angle. UV=|U|*|V|*Cos, where 
  257. is the angle between U and V. Incidentally, if |U|=1 then this
  258. simplifies to |V|*Cos, which is the length of the projection of
  259. V onto U. It is of note that UV is 0 if and only if either  is
  260. /2+2k or |U|=0 or |V|=0. Assuming |U| and |V| are not 0, this
  261. means that if UV is 0, then U and V are perpendicular, or
  262. orthogonal.
  263.  
  264. The second product usually defined on vectors is the cross
  265. product. U cross V (usually noted UV) is defined using matrix
  266. determinant and somesuch. Basically, (u1,u2,u3)(v1,v2,v3) is
  267. u1*(v2-v3)+u2*(v3-v1)+u3*(v1-v2).
  268.  
  269. It is demonstratable that the cross product of two vectors is
  270. perpendicular to the two vectors and has a length of |U||V|Sin.
  271. The fact that it is perpendicular has applications that we will
  272. see later.
  273.  
  274. Exercises
  275.  
  276. Q1 - Do the following vector operations:
  277.  
  278.     a) (1,3,2)+(3,5,6)
  279.  
  280.     b) 1.5*(3,4,2)
  281.  
  282.     c) (-1,3,0)(2,5,2)
  283.  
  284.     d) |(3,4,20/3)|
  285.  
  286.     e) UV where |U|=2, |V|=3 and the angle between U and V is 60
  287. degrees
  288.  
  289.     f) (1,2,3)(4,5,6)
  290.  
  291. Q2 - Which vectors satisfy the equation U(1,1,1)=0?
  292.  
  293. Answers
  294.  
  295. A1 -     a) (4,8,8)
  296.  
  297.     b) (4.5,6,3)
  298.  
  299.     c) 13
  300.  
  301.     d) 25/3
  302.  
  303.     e) 3
  304.  
  305.     f) 0
  306.  
  307. A2 -    All vectors that satisfy u1+u2+u3=0. Since the dot product
  308. is 0, this means all vectors that are perpendicular to U.
  309. Incidentally, these vectors cover the whole plane and nothing
  310. but the plane for which the normal is (1,1,1).
  311.  
  312. Alcoholism and dependance
  313.  
  314. Given a set of vector U0, U1, U2, ... , Un, these vectors are
  315. said to be linearly independant if and only if the following is
  316. true:
  317.  
  318. a0*U0+a1*U1+...+an*Un=0 implies that (a0,a1,a2, ... , an)=0.
  319.  
  320. If there exists a single solution for which (a0, a1, a2, ...,an)
  321. is not zero, then there exist an infinity of them, and the
  322. vector are said to be linearly independant.
  323.  
  324. The geometric interpretation of that is as follows. In 3d, three
  325. vectors are linearly independant if none of them are colinear
  326. and the three of them are not coplanar. (Colinear means on the
  327. same line, coplanar means on the same plane). Any more than 3
  328. vectors and they are certain to be linearly dependant.
  329.  
  330. For two vectors, in 2d or 3d, they are said to be linearly
  331. independant if they are not colinear. 3 or more vectors in 2d
  332. are always linearly dependant.
  333.  
  334. If a set of vectors are linearly independant, they are said to
  335. form a basis. 2 linearly independant vectors form the basis for
  336. a plane, and 3 linearly independant vectors form the basis for a
  337. 3d space.
  338.  
  339. The term orthogonal is very frequently used to described
  340. parallel vectors. If a basis is said to be made of orthogonal
  341. unit vectors, the base is said to be orthonormal. Orthonormal
  342. basis are the most useful kind in usual 3d graphics. If a basis
  343. is not orthonormal, it "skews" the space, where if the vectors
  344. are not unit, it "stretches" and/or "compresses" the space.
  345.  
  346. Each space has a so-called canonical basis, the basis we
  347. intuitively find most simple. For 3d space, that basis is made
  348. of the vectors (1,0,0), (0,1,0) and (0,0,1). Similarly, the
  349. canonical basis for 2d space is (1,0) and (0,1). Note that since
  350. a basis is a set of vectors, it would be more formal to enclose
  351. the list of vectors in curly braces, for example, {(2,3) ,
  352. (-1,0)}.
  353.  
  354. The vectors of the canonical basis are traditionnally noted i, j
  355. and k for 3d space or i and j for 2d space. This leads us to
  356. introduce another notation.
  357.  
  358. If vector (a,b,c) is said to be expressed in basis pqr, then it
  359. means that the vector is a*p+b*q+c*r. Note that a, b and c are
  360. scalars and p, q and r are vectors, thus this combination
  361. (formally referred to as linear combination) is defined as
  362. discussed earlier. If pqr are ijk, this translates to
  363. a*i+b*j+c*k or (a,0,0)+(0,b,0)+(0,0,c) or (a,b,c).
  364.  
  365. However, if pqr is not ijk, the matter is different. For example
  366. (assuming pqr is expressed in ijk space), if p=(1,1,0),
  367. q=(0,1,1) and r=(1,0,1), then the vector (a,b,c) in pqr space
  368. means (a,a,0)+(0,b,b)+(c,0,c)=(a+c,a+b,b+c) in ijk space. What
  369. we just did is called a change of basis. We took a vector that
  370. was expressed in pqr space and expressed it in ijk space.
  371.  
  372. It would be possible for pqr to be expressed in some other base
  373. than the canonical base. If that were the case, and if the
  374. objective would be to express vector (a,b,c) in ijk space, then
  375. it might require several transformations to get there.
  376.  
  377. For simplicity's sake in the further parts of this document, we
  378. will extend our definition of vectors to allow for not only real
  379. number components, but also vector components. This means that
  380. (a,b,c) expressed in pqr space is a*p+b*q+c*r can be written as
  381. (a,b,c)(p,q,r).
  382.  
  383. Exercises
  384.  
  385. Q1 - Are the vectors (1,2,0), (4,2,4) and (-10,-4,-8) linearly
  386. independant?
  387.  
  388. Q2 - Say vector U=(1,3,2) is expressed in pqr space, where pqr
  389. expressed in ijk space is (1,2,0), (2,0,2), (0,-1,-1). Express U
  390. in ijk space.
  391.  
  392. Q3 - Using Question 2's values for p, q and r, and the vector V
  393. expressed in ijk space as (1,1,1), can you express V in pqr
  394. space?
  395.  
  396. Answers
  397.  
  398. A1 - No
  399.  
  400. A2 - (7,0,4)
  401.  
  402. A3 - (4/3, -1/6, -5/6) - this exercise is in fact called an
  403. inverse transform, which will be described later.
  404.  
  405. On a plane (and of motion sickness)
  406.  
  407. There are several ways to define a plane in 3d. The first one I
  408. will present is useful because it can be used to represent a
  409. plane in n dimensional space, even for n>3.
  410.  
  411. First you need two linearly independant vectors to form a basis.
  412. Call them U and V. Then, if you take a*U+b*V for all possible
  413. values of a and b (them being real numbers of course), you
  414. generate a whole plane that goes through the origin of space. If
  415. you want to displace that plane in space by vector W (e.g. you
  416. want the point pointed to by W to be part of the plane), then
  417. a*U+b*V+W will generate the desired plane. (Proof, for a=b=0, it
  418. simplifies to W, thus the point at W is part of the plane).
  419.  
  420. Note that the above equation can be written (a,b)(U,V)+W. As
  421. such it can be viewed as a change of basis, from the canonical
  422. basis of 2d space to whatever space U and V's basis is.
  423.  
  424. Another way for defining a plane that only works in 3d is as
  425. follows. (Note, in n dimensional space, this will define a n-1
  426. dimensional object). As was seen earlier, if AX=0, then A and X
  427. are perpendicular (A and X are vectors). Furthermore, for a
  428. given A, if you take all X's that satisfy the equation, you get
  429. all points in a certain plane. A is generally called normal to
  430. the plane, although the litterature frequently assumes that the
  431. normal is also of unit length, which is not necessary (though A
  432. must not be the null vector). The values of X that satisfy the
  433. plane equation given include X=0, since A0=0 for any value of A.
  434. Thus, that plane passes through the origin.
  435.  
  436. If one wants a plane that does not pass through the origin, one
  437. should proceed as follow. (This uses an intuitive form of affine
  438. transformations, descibed in depth later). First, find out the
  439. displacement vector K that describes the position of the plane
  440. in relation to the origin. Thus, if you subtract K from all the
  441. points in the plane, the plane ends up at the origin, and we can
  442. use the definition above. Thus, the new definition of the plane
  443. is A(X-K)=0.
  444.  
  445. To make this a bit more explicit, let A=(A,B,C) and X=(x,y,z)
  446. and K=(k1,k2,k3). Then the plane equation can be rewritten as:
  447. A*(x-k1)+B*(y-k2)+C*(z-k3)=0. A little algebra allows us to
  448. rewrite it as A*x+B*y+C*z=-A*k1-B*k2-C*k3. By setting
  449. D=-A*k1-B*k2-C*k3, we can make one more rewrite, which is the
  450. final form: A*x+B*y+C*z=D.
  451.  
  452. It is important to remember that multiplying both side of the
  453. equation by a constant does not change the plane. Thus, plane
  454. x+y+z=1 is the same as plane 2x+2y+2z=2.
  455.  
  456. Note that in this last representation, (A,B,C) is the normal
  457. vector to the plane. The last equation can also be re-written
  458. AX=D. It would also be easy to demonstrate the following, but I
  459. will not do it. For any point P, (AP-D)/|A| is the signed
  460. distance to the plane AX=D. The sign can help you determine on
  461. what side of the plane that the point P lies on. If it is 0, P
  462. is on the plane. If it is positive, P is in the direction that
  463. the normal points to. If it is negative, P is on the side
  464. opposite of the normal. This has application in visible surface
  465. determination (namely, back face culling).
  466.  
  467. Also note that if |A|=1, then the distance equation simplifies
  468. to AP-D.
  469.  
  470. It is trivial to demonstrate that the equation for a line in
  471. n-space, for any integer value of n>0, is t*U+W, where U is a
  472. vector parallel to the line and W is a point on the line. As t
  473. takes all real values, we generate a line.
  474.  
  475. Exercises
  476.  
  477. Q1 - Given the basis U=(1,3,2) and V=(2,2,2), and the position
  478. vector W=(1,1,0), find the position in 3d space of the point
  479. (3,2) in UV space.
  480.  
  481. Q2 - Express the plane described in Q1 in the form Ax+By+Cz=D
  482.  
  483. Q3 - Find the signed distance of point (4,2,4) to the plane
  484. using the answer for question 2.
  485.  
  486. Q4 - Given two basis vectors for a plane, P and Q, in 3d space,
  487. and a position vector for the plane, R, plus the direction
  488. vector of a line, M, that passes through origin, find the pq
  489. space point of intersection between the line and the plane.
  490.  
  491. Anwers
  492.  
  493. A1 - (8,14,10)
  494.  
  495. A2 - x+y-2z=2 (hint : remember that the cross product of U and V
  496. is perpendicular to both U and V).
  497.  
  498. A3 - -4/(61/2)-1.633 - this means that the point (4,2,4) is in
  499. the direction opposite of (1,1,-2) from the plane x+2-2z=2.
  500.  
  501. A4 - See the perspective chapter on texture mapping.
  502.  
  503. Matrix mathematics
  504.  
  505. Introduction
  506.  
  507. Matrices are a tool used to handle a great deal of linear
  508. combinations in a homogeneous way. The operations on matrices
  509. are so defined as to ease whatever task you want to do with
  510. them. Be it expressing a system of equations, or making a change
  511. of basis, to some peculiar uses in calculus.
  512.  
  513. Normally, matrices are noted using large parenthesis and the
  514. numbers written down in a grid-like disposition as follows. This
  515. is a generic 3x3 matrix:
  516.  
  517.  
  518.  
  519. In general, a pxq matrix is noted as above with the exception
  520. that it has p rows and q columns. The above matrix can also be
  521. written M=(mij) with i and j varying from 1 to 3.
  522.  
  523. A matrix for which p=q, such as the M matrix above, is said to
  524. be a square matrix. There exist a particular type of square
  525. matrix called an identity matrix. There is one such matrix for
  526. each type of square matrix (e.g. one for 1x1 matrices, one for
  527. 2x2 matrices, one for 3x3 matrices, etc...) As an example, the
  528. 3x3 matrix is given here:
  529.  
  530.  
  531.  
  532. Strictly speaking, the identity matrix I=(mij) is defined such
  533. as:
  534.  
  535. mij=0 if ij    and    mij=1 if i=j
  536.  
  537. Matrix operations
  538.  
  539. Matrix addition is defined as follow. Given 2 matrices A=(aij)
  540. and B=(bij) of same dimension pxq, then U=(uij)=A+B is defined
  541. as being (uij)=(aij+bij).
  542.  
  543. Matrix multiplication by a scalar is defined also as follows.
  544. Given the matrix M and a scalar k, then the operation
  545. U=(uij)=k*M is defined as (uij)=(k*mij).
  546.  
  547. Matrix multiplication is a bit more involved. It is defined
  548. using sums, as follows. Given matrix A of dimension pxq, and
  549. matrix B of dimension qxr, the product C=AxB is given by:
  550.  
  551. (cij)=1kq(aik*bkj)
  552.  
  553. More explicitly, for example, we have, for A and B 2x2 matrices:
  554.  
  555. c11=a11*b11+a12*b21
  556.  
  557. c12=a11*b12+a12*b22
  558.  
  559. c21=a21*b11+a22*b21
  560.  
  561. c22=a21*b12+a22*b22
  562.  
  563. (Note: 1kq(aik*bkj) means "sum of (aik*bkj) for k varying from 1
  564. to q.")
  565.  
  566. It is important to notice that matrix multiplication is not
  567. commutative in the general case. For example, it is not true
  568. that A*B=B*A with A and B matrices in the general case, even if
  569. A and B are square matrices. Matrix multiplication is, however,
  570. associative.
  571.  
  572. The identity matrix has the property that, for any matrix A,
  573. A*I=I*A=A (I is the neutral element of matrix multiplication).
  574.  
  575. Matrix transposition of matrix A, noted AT, reflects the A
  576. matrix along the great diagonal. That is, say A=(aij) and
  577. AT=(bij), then we have bij=aji.
  578.  
  579. There are also other interesting operations you can do on a
  580. matrix, however they are much, much more involved. As of now, I
  581. am not willing to get too deeply into this. The topics of
  582. interest are matrix determinant (which has a recursive
  583. definition) and matrix inversion. I will content myself by
  584. giving one definition of matrix determinant and one way of
  585. finding matrix inverse. Note that there are at least a couple of
  586. different definitions for determinant, though they boil down to
  587. the same thing. Also, there are many ways of finding the inverse
  588. of a matrix, I will contend myself with presenting only one
  589. method. Strict definitions will be given, for more extensive
  590. coverage, consult a linear algebra book.
  591.  
  592. Given a matrix M=(mij), of size 1x1, the determinant is defined
  593. as D=m11. For matrices of size nxn with n>1, the definition is
  594. recursive. First, pick an integer j such that 1jn. For example,
  595. you could pick j=1.
  596.  
  597. D=mj1*Cj1+mj2*Cj2+...+mjn*Cjn
  598.  
  599. The Cij terms require a bit more explaining, which follows.
  600.  
  601. First let us define the minor matrix Mij of matrix M. If M is a
  602. nxn matrix, then the Mij matrix is a (n-1)x(n-1) matrix. To
  603. generate the Mij matrix, remove the ith line and jth column from
  604. the M matrix.
  605.  
  606. Second what interests us is the cofactor Cij, which is defined
  607. to be:
  608.  
  609. Cij=(-1)i+j*|Mij|, where |Mij| denotes the determinant of Mij.
  610.  
  611. As an example, the determinant of the 2x2 matrix M is
  612. m11*m22-m12*m21, and the determinant of a 3x3 matrix M is 
  613.  
  614. D3x3=    m11*(m22*m33-m23*m32)
  615.  
  616.     - m12*(m21*m33-m23*m31)
  617.  
  618.     + m13*(m21*m32-m22*m31)
  619.  
  620. Given a matrix A, the inverse of the matrix, noted A-1 (if it
  621. exists), is such that A*A-1=A-1*A=I. It is possible that a
  622. matrix has no inverse.
  623.  
  624. To inverse the matrix, we will first define the adjacent matrix
  625. of A, which we will call B=(bij). Let Cij denote the i,j
  626. cofactor of A. Then, we have:
  627.  
  628. bij=Cij
  629.  
  630. Which completely defines the cofactor matrix B. The inverse of A
  631. is then:
  632.  
  633. A-1=1/|A|*BT
  634.  
  635. Another method of inverting matrices, which might be preferable
  636. for numerical stability reasons but will not be discussed here,
  637. is the Gauss-Jordan method.
  638.  
  639. Exercise
  640.  
  641. Q1 - Compute the product of these two matrices:
  642.  
  643.  
  644.  
  645. Answer
  646.  
  647. A1
  648.  
  649.  
  650.  
  651. Matrix representation & linear transformations
  652.  
  653. The following set of equations:
  654.  
  655. m11*x+m12*y+m13*z=A
  656.  
  657. m21*x+m22*y+m23*z=B
  658.  
  659. m31*x+m32*y+m33*z=C
  660.  
  661. is equivalent to the matrix equation that follows:
  662.  
  663.  
  664.  
  665. It is also equivalent to the following vector equations
  666.  
  667. P=(m11,m21,m31), Q=(m12,m22,m32), R=(m13,m23,m33)
  668.  
  669. X=(x,y,z)
  670.  
  671. D=(A,B,C)
  672.  
  673. D=X(P,Q,R)
  674.  
  675. This means that matrix can be used, amongst other things, to
  676. represent systems of equations, but also a change of basis. Look
  677. back on the vector mathematics chapter and you will see that
  678. D=X(P,Q,R) litterally means "transform X, which is expressed in
  679. PQR space, in whatever space PQR is expressed in (could be ijk
  680. space for example), the answer is labeled D."
  681.  
  682. The matrix form can also be written as follows:
  683.  
  684. M*X=D
  685.  
  686. In this case, if the matrix M is inversible, then we can
  687. premultiply both sides of the equality by M-1, as follows:
  688.  
  689. M-1*M*X=M-1*D
  690.  
  691. And, knowing that M-1*M=I, we substitute into the above:
  692.  
  693. I*X=M-1*D
  694.  
  695. And knowing that I*X=X, we finally get:
  696.  
  697. X=M-1*D
  698.  
  699. That is a very elegant, efficient and powerful way of solving
  700. systems of equations. The difficulty is of course finding M-1.
  701. For example, if we know M, D but not X, we can use the above to
  702. find X. This is what should be used to solve question 3 in
  703. chapter "Alcoholism and dependance". For 3d graphics people,
  704. this is the single most useful application of matrix inversion:
  705. sometimes you have a point in ijk space, and you want to express
  706. them in pqr space. However, you don't originally have ijk
  707. expressed in pqr space, but you have pqr expressed in ijk space.
  708. You will then write the transformation of a point from pqr space
  709. to ijk space, then find the inverse transformation as just
  710. described and then inverse transform the point to find it's
  711. position in pqr space.
  712.  
  713. Another very interesting aspect is as follows. If we have a
  714. point P to be transformed by matrix M, and then by matrix N.
  715. What we have is:
  716.  
  717. P'=M*P
  718.  
  719. P''=N*P'
  720.  
  721. By combining these two equations, we get
  722.  
  723. P''=N*(M*P)
  724.  
  725. However, by associativity of matrix multiplication, we have:
  726.  
  727. P''=(N*M)*P
  728.  
  729. If for instance, we plan to process a great many points through
  730. these two transformations in that particular order, it is a
  731. great time saver to be able to first calculate A=N*M, and then
  732. simply evaluate P''=A*P for all P's, instead of first
  733. calculating P' then P''. In linear transformations terminology,
  734. A is said to be the linear combination of M and N.
  735.  
  736. Affine transforms
  737.  
  738. Introduction
  739.  
  740. As of now, we have seen linear transformations. Linear
  741. transformations can be used to represent changes of basis.
  742. However, they fail to take into account possible translation,
  743. which is of top priority to 3d graphics. An affine transform is,
  744. roughly, a linear transform followed by a translation (or
  745. preceded, though it is more useful for 3d graphics to picture
  746. them as being followed by the translation instead).
  747.  
  748. Affine transformations
  749.  
  750. A simple proof can be used to demonstrate that a 3x3 matrix
  751. cannot be used to translate a 3d point. Given any 3x3 matrix A
  752. and the point P=(0,0,0), then A*P=(0,0,0), thus the point is
  753. untranslated. It is merely rotated/skewed/stretched about the
  754. origin.
  755.  
  756. However, there is a neat trick. A linear transform in 4d space
  757. projected in a particular fashion in 3d space is an affine
  758. transformation. Without going into the details, a 4x4 matrix can
  759. be used to model an affine transform in 3d. The matrix has the
  760. following form:
  761.  
  762.  
  763.  
  764. The (mij) 3x3 submatrix is the normal rotation/skew/stretch (the
  765. linear transform we studied previously). The (Tx,Ty,Tz) vector
  766. is added to the point after transform. A point (x,y,z) to be
  767. transformed into (p,q,r) is noted:
  768.  
  769.  
  770.  
  771. Another way of modelling affine transform is to use the
  772. conventional 3x3 matrix we were using previously, and to add a
  773. translation vector after each linear transform. The advantage of
  774. this is that we do not do unnecessary multiplications for
  775. translation and also the bottom row of the 4x4 matrix which is
  776. (0,0,0,1) that can be optimized out. However, the advantage of
  777. using the 4x4 matrix on the conceptual level (not on the
  778. implementation level) is that you can then compute affine
  779. transformation combinations and inversions, the exact same way
  780. that we were doing in the previous section.
  781.  
  782. Applications of linear transformations
  783.  
  784. Introduction
  785.  
  786. In this section we will discuss the applications of the linear
  787. transformation theory we saw in the previous sections. When
  788. doing 3d graphics, the usual situation occurs. We have a
  789. description of one or more objects. We have their locations and
  790. orientations in space, relative to some point of reference. We
  791. move them around, rotate them, usually about their own
  792. coordinate system. The camera might also be moving, rotating and
  793. such. In that case, it is likely that we have an orientation and
  794. position for the camera object itself. We would also like that
  795. the eye points in the direction of (0,0,1) in camera space, and
  796. that up be (0,1,0) in camera space.
  797.  
  798. Orientation and position will be given by an affine transform
  799. matrix. The (mij) submatrix gives orientation and the 4th column
  800. has the translation vector.
  801.  
  802. World space, eye space, object space, outer space
  803.  
  804. First off we are going to require a global system of reference
  805. for all the objects. This is usually called "World space". An
  806. affine transform that describes an object's position and
  807. orientation usually does so in relation to world space (this is
  808. generally not true for hierarchical structures, as we will see
  809. later). This introduces a new concept; a matrix A, representing
  810. an affine transform that takes an object from space M to space N
  811. (in our example, M is object space and N is world space) is
  812. usually noted ANM. This has the natural tendency to make us
  813. combine the affine transform from right to left instead of left
  814. to right, which is correct (see a preceding section).
  815.  
  816. The most typical example is as follows. We have an object and
  817. its affine transform AWorldObject. We also have a camera
  818. position and orientation given by CWorldCamera. In that case,
  819. the first thing we want to do is invert the transform
  820. CWorldCamera to find the CCameraWorld transform. Then you will
  821. be transforming the points Pi in the object with
  822. CCameraWorld*AWorldObject*Pi.
  823.  
  824. As a helper, notice that the little arrows make a lot of sense,
  825. as shown below:
  826.  
  827. CameraWorld, WorldObject, which concatenates intuitively to
  828. CameraWorldObject or simply CameraObject. Thus, the above
  829. transformation transforms from object space to camera space
  830. directly. One merely calculates
  831. MCameraObject=CCameraWorld*AWorldObject and multiplies all Pi's
  832. with is.
  833.  
  834. Transformations in the hierarchy (or the French revolution)
  835.  
  836. It may be useful to express an object A's position and
  837. orientation relative not to the world, but to some other object
  838. B. This way, if B moves, A moves along with it. In plain words,
  839. if we say "The television is resting 2 centimeters above the
  840. desk on its four legs", then moving the desk does not require us
  841. to change our "2 centimeters above the desk" position - it is
  842. still 2 centimeters above the desk as it is moving along with
  843. the desk (careful not to drop it). On the other hand, if we had
  844. said "The television is 1 meter above the floor" and "The desk
  845. is 95 centimeters above the floor", and then proceed to move the
  846. desk up 1 meter, then the position of the desk is "1m95 above
  847. the floor". Additionnally, we have to edit the position of the
  848. television and change it to "The telebision is 2 meters above
  849. the floor". Notice the difference between these two examples.
  850.  
  851. This can be implemented very easily the following way. Make an
  852. affine transform that describes orientation and position of
  853. television in relation to the desk. This is called
  854. ADeskTelevision. Then we have an orientation and position for
  855. the desk, given by BWorldDesk. Notice that this last affine
  856. transform is relative to world space. We then of course have the
  857. mandatory CWorldCamera which we invert to find the CCameraWorld
  858. transform. We then proceed to transform all points in the
  859. television to camera space, and also all points from the desk to
  860. camera space. The former is done as follows:
  861.  
  862. CCameraWorld*BWorldDesk.*ADeskTelevision*Pi.
  863.  
  864. Notice again how the arrows concatenate nicely. The points on
  865. the desk are transformed with this:
  866.  
  867. CCameraWorld*BWorldDesk.*Qi.
  868.  
  869. Again, the arrows make all the sense in the world.
  870.  
  871. Some pathological matrices
  872.  
  873.  
  874.  
  875. Rotating a point in 2d is fundamental. In the example above, we
  876. wish to rotate (x,y) to (x',y') by an angle of b. The following
  877. can be said:
  878.  
  879. y'=sin(a+b)r        x'=cos(a+b)r
  880.  
  881. With the identities sin(a+b)=sin(a)cos(b)+sin(b)cos(a) and
  882. cos(a+b)=cos(a)cos(b)-sin(a)sin(b), we substitute.
  883.  
  884. y'=rsin(a)cos(b)+rcos(a)sin(b)
  885.  
  886. x'=rcos(a)cos(b)-rsin(a)sin(b)
  887.  
  888. But from figure 3 we know that
  889.  
  890. rsin(a)=y    and    rcos(a)=x
  891.  
  892. We now substitute:
  893.  
  894. y'=ycos(b)+xsin(b)
  895.  
  896. x'=xcos(b)-ysin(b)
  897.  
  898. Rotation in 3d are done about one of the axis. The exact
  899. rotation used above would rotate about the z axis. In matrix
  900. representation, we write the x, y and z axis rotations as
  901. follows:
  902.  
  903.  
  904.  
  905. These matrices can be extended to 4x4 matrices simply by adding
  906. a rightmost column vector of (0,0,0,1) and a bottom row vector
  907. of (0,0,0,1) (e.g. the 1 in the bottom right slot is shared by
  908. the column and the row vector).
  909.  
  910. If you want, you can always specify the orientation of an object
  911. using three angles. These are formally referred to the euler
  912. angles. Unfortunately, these angles are not too useful for many
  913. reasons. If two angles change with linear speed, the object will
  914. definetly not rotate in a linear fashion. Also, sometimes, a
  915. problem known as gimbal lock occurs, where you suddenly lose one
  916. degree of freedom (this looks like the object's rotation in a
  917. direction stops, to start again in another strange direction).
  918. Furthermore, the angles are not relative to object coordinate
  919. system nor world coordinate system.
  920.  
  921. Thus it is preferable to specify object orientation with an
  922. orientation matrix. When rotation about a world axis is desired,
  923. the orientation matrix is premultiplied by one of the above
  924. rotation matrices, and when a rotation about an object axis is
  925. desired, the orientation matrix is postmultiplied by one of the
  926. above rotation matrices. Note that it is possible to rotate
  927. about an arbitrary vector when using quaternions, but this will
  928. not be covered here.
  929.  
  930. Perspective
  931.  
  932. Introduction
  933.  
  934. Perspective was a novelty of the Renaissance. It existed a long
  935. time before but had been forgotten by the western civilizations
  936. until that later time. As can be seen from paintings before
  937. Renaissance, artists had a very poor grasp of how things should
  938. appear on a painting. The edges from tables and desks were not
  939. drawn converging to an "escape point", but rather all parallel.
  940. This gave these paintings the peculiar feeling they have when
  941. compared to more modern, more perspective-correct paintings.
  942.  
  943. Perspective is the name we give to that strange distortion that
  944. happens when you take a real-life 3d scene (your garden) and
  945. take a picture of it. The flowers in the foreground appear
  946. larger than the barn in the background. This particular effect
  947. is sometimes referred to as foreshortening. Other effects come
  948. into play, such as focus blur (very likely, you were either
  949. focussed on the flower or the barn; one looks clear, the other
  950. is very fuzzy), light attenuation, atmospheric attenuation,
  951. etc...
  952.  
  953. We know today that light rays probably aren't moving in a
  954. straight line at all. Even in the vacuum, they oscillate a bit.
  955. When travelling through matter, it is deviated all the time,
  956. split, reflected and all sorts of other nonsense. Sometimes it
  957. can be useful to model all these nice effects, however, they are
  958. not always necessary or desirable. One thing is for sure, a
  959. perfect or near-perfect simulation of all that we know about
  960. light today would be tremendously CPU-intensive, and would
  961. require an incredible amount of work on the software end of the
  962. project.
  963.  
  964. In normal, day-to-day life, when you're significantly larger
  965. than an atom but significantly smaller than a planet, light is
  966. usually pretty linear. It travels in straight rays, only bending
  967. at discrete points that are more or less easy to calculate,
  968. definetly more than the fuzzy way light bends in a prism.
  969.  
  970. A further simplification that we can make is that light only
  971. reflects diffusely on the objects around you. This is usually
  972. the case, unless you come up to a highly polished or metallic
  973. surface where you can see your reflection. But the usual desk,
  974. bed, snake and computers are pretty dull in appearance, with
  975. usually a soft diffuse highlight from where the light is coming
  976. from.
  977.  
  978. Another simplification we usually make comes from the fact that
  979. light bounces off everything and eventually starts coming from
  980. about all direction with a low intensity. This is often called
  981. the ambiant light. Some further optimizations, more hacks than
  982. actual physical observations, will make you go faster and still
  983. look good.
  984.  
  985. The perspective transformation
  986.  
  987.  
  988.  
  989. The perspective transformation is incredibly simple once you
  990. know it, but it is often good to know where it comes from. We
  991. will put to use some of the assumptions we previously stated.
  992.  
  993. The first assumption we made is that light goes in a straight
  994. line. This is great because it will allow us to make maximum use
  995. of all the linear math we have learnt since highschool.
  996.  
  997. What we have to realize is, for the eye to see an object, light
  998. has to travel from the object to the eye. Since light travels in
  999. a straight line, it has to either go straight to the eye or
  1000. bounce off a few reflective surfaces before getting there.
  1001. However, since we are assuming there are no such reflective
  1002. surfaces in the environment, the only possibility left is that
  1003. the light comes straight from the object to the eye. This line
  1004. is formally refered to as a projector.
  1005.  
  1006. Another way doing it is the exact inverse. Starting from the
  1007. eye, shoot a ray in a direction until it hits something. That is
  1008. what you are seeing in that direction.
  1009.  
  1010. Obviously, we are not going to shoot an infinite number of rays
  1011. in all direction, we would never even start generating an image
  1012. if we did that. The usual approximation is to shoot a finite
  1013. amount of rays spread over an area in an arbitrary manner.
  1014.  
  1015. There is another matter that needs to be taken care of. In
  1016. reality, the image will be sent to screen, paper or some other
  1017. media. This means that, in our model, the light does not reach
  1018. the eye, it stops at the screen or paper, and that is what we
  1019. display, so that reality takes over for the rest of the way and
  1020. carries real light rays from the screen to the real eyes. This
  1021. poses a problem of finding where the light rays intersect the
  1022. screen or paper.
  1023.  
  1024. Using the material in the previous section, we are able to
  1025. transform all objects to camera space, where forward is (0,0,1)
  1026. and up is (0,1,0) and the eye is at (0,0,0). We still do not
  1027. know where in space the screen lies. We will have to make a few
  1028. more assumptions, that it is in front of the eye, perpendicular
  1029. to the eye direction which is (0,0,1), and flat. The distance at
  1030. which it lies is still undecided. We will just work with the
  1031. constant k for the distance, then see what value of k interests
  1032. us most. The eye is formally refered to as center of projection,
  1033. and the plane the surface of projection.
  1034.  
  1035. Since it is flat, it lies on a plane. The plane equation in
  1036. question is Ax+By+Cz=D as seen before, where (A,B,C)=(0,0,1) is
  1037. the plane normal. Thus the plane equation is z=D. The distance
  1038. from the eye is thus D, and we want it to be k, so we set D=k.
  1039. The plane equation is therefore z=k. We set a local basis for
  1040. that plane with vectors i=(1,0,0) and j=(0,1,0) and position
  1041. W=(0,0,k). The plane equation is thus (a,b)(i,j)+W. (a,b) are
  1042. the local coordinates on the plane. They happen to correspond to
  1043. the (x,y) position on the plane in 3d space because (i,j) for
  1044. the plane is the same as (i,j) for the world.
  1045.  
  1046. The question we now ask ourselves is this: given a point that is
  1047. reflecting light, say point (x,y,z), what point on screen should
  1048. be lit that crosses the light ray from (x,y,z) to the eye, which
  1049. is at (0,0,0).
  1050.  
  1051. Here we will use the definition of the line in n space we
  1052. mentionned before (namely, tV+W). Since the light ray goes from
  1053. (x,y,z) to (0,0,0), it is parallel to the vector
  1054. (x,y,z)-(0,0,0)=(x,y,z). Thus, we can set V=(x,y,z). (0,0,0) is
  1055. a point on the line, so we can set W=(0,0,0). The line equation
  1056. is thus t(x,y,z).
  1057.  
  1058. We now want the intersection of the line t(x,y,z) with the plane
  1059. z=k. Setting t=k/z (assuming z is nonzero), we find the
  1060. following: k/z(x,y,z)=(k*x/z,k*y/z,k). This point has z=k thus
  1061. it is in the plane z=k, thus it is the intersection of the plane
  1062. z=k and the line t(x,y,z).
  1063.  
  1064. Trivially from that, we find that the point (a,b) on screen are
  1065. (k*x/z,k*y/z). Thus,
  1066.  
  1067. (x,y,z) perspective projects to (k*x/z, k*y/z).
  1068.  
  1069. A small note on aspect ratios. Sometimes, a screen's coordinate
  1070. system is "squished" on one axis. In this case, it would be wise
  1071. to "expand" one of the coordinates to make it larger to
  1072. compensate for the screen being squished. For example, if the
  1073. screen pixels are 3/4 as wide as they are high, it would be wise
  1074. to multiply the b component of screen position by 3/4, or the a
  1075. component by 4/3. This can be computed using 2 different values
  1076. of k instead of the same. For example, use k1=k and k2=ratio*k.
  1077. Then, the perspective projection equation is:
  1078.  
  1079. (x,y,z) perspective projects to (k1*x/z, k2*y/z).
  1080.  
  1081. Referring again to physics, only one point gets to be projected
  1082. to a particular point on screen. That is, closer objects obscure
  1083. objects farther away. It will thus be useful to do some form of
  1084. visible surface determination eventually. Another special case
  1085. is that anything behind the eye does not get projected at all.
  1086. Thus, if before the projection, z0, do not project.
  1087.  
  1088. Theorems
  1089.  
  1090. The following theorems are not always entirely obvious, but they
  1091. are of great help when doing 3d graphics. I will attempt to give
  1092. the reader rough proofs and justifications when possible,
  1093. usually they will be geometrical proofs for they are much more
  1094. natural in this case. These proofs are not very formal, but
  1095. formal proofs are not hard to find, just much less natural.
  1096.  
  1097. A line in 3d perspective projects to a line in 2d. However, line
  1098. segments sometimes have erratic behavior. The proof is as
  1099. follows. If the object to project is a line, then the set of all
  1100. projectors pass through the center of projection, which is a
  1101. point, and the line. Since projector are linear, they all belong
  1102. to the plane P defined by the line and the point. Thus, the
  1103. projection will lie somewhere in the intersection of the plane P
  1104. and the projection plane. However, the intersection of two
  1105. planes is generally a line. Here follows the exception.
  1106.  
  1107. If the planes are parallel, since the projection plane does not
  1108. pass on the eye, they are necessaraly disjoint. The projection
  1109. in this case is nothing.
  1110.  
  1111. A line segment generally projects to a line segment. First, the
  1112. only portion of the line segment that needs to be projected is
  1113. the portion for which z>0, as seen previously. If the segment
  1114. crosses z=0, it should be cut at z=0, and only the z>0 section
  1115. kept. Second, the projectors for a line segment all lie in a
  1116. scaled up triangle which intersects the projection plane in a
  1117. particular way, and the intersection of a triangle and a plane
  1118. is always a line segment.
  1119.  
  1120. Next proof is the proof that a n-gon (a n-sided polygon,
  1121. example, triangles are 3-gons, squares are 4-gons, etc...)
  1122. projects to a n-gon. It can be demonstrated that any polygon can
  1123. be triangulated in a finite set of triangles, so the proof is
  1124. kept to triangles only. Also, if the n-gon crosses z=0, it
  1125. should be cut at z=0, and only the z>0 section kept.
  1126.  
  1127. A triangle projects to a triangle. The projectors of a triangle
  1128. all lie in an infinitely high tetrahedron, and the intersection
  1129. of an infinitely high tetrahedron and the projection plane, in
  1130. the non-infinite direction is always a triangle.
  1131.  
  1132. In a similar line of thought, the set of all projectors of a
  1133. sphere form a cone. The intersection of the cone with the
  1134. projection plane can form any conic. Namely, a hyperbola, an
  1135. ellipse or a circle. If the sphere contains the origin, the
  1136. projection fills the whole projection plane.
  1137.  
  1138. Other applications
  1139.  
  1140. By not losing sight of the idea behind the projection, one can
  1141. accomplish much more than what has been just described. One
  1142. example is texture mapping. Often, a polygon will be drawn on
  1143. screen, but some properties of the polygon (say color for
  1144. example) changes across the polygon in 3d space. When this
  1145. happens, we want to know what point from the polygon we are
  1146. currently drawing. An application of this is texture mapping.
  1147.  
  1148. Texture mapping involves taking the point on screen, finding the
  1149. projector that goes through it and finding the intersection of
  1150. that projector with the polygon. We then have a point in 3d
  1151. space. However, it is usually much more useful to make a local
  1152. 2d coordinate system for the plane containing the polygon and
  1153. make the property a function of the location in that 2d
  1154. coordinate system. This is what I did below in the snapshot of
  1155. the screen from my math software.
  1156.  
  1157.  
  1158.  
  1159. As can be quite plainly seen above, the equations for p and q
  1160. above are of the form:
  1161.  
  1162. p=(Du+Ev+F)/(Au+Bv+C)
  1163.  
  1164. q=(Gu+Hv+I)/(Au+Bv+C)
  1165.  
  1166. Notice that the denominator is the same for both p and q. The
  1167. values for the coefficients A through I can be found by
  1168. examining the snapshot of the math software screen above.
  1169.  
  1170. Other applications can also be found to the theory. A popular
  1171. application is for the rendering of certain types of space
  1172. partitions, popularly referred to as voxel spaces. Start with a
  1173. short vector in the direction you want to shoot the light ray,
  1174. and start at the eye. Move in short steps in the direction of
  1175. the light ray until you hit an obstacle, and when you do, color
  1176. the screen point with the color of the obstacle you hit.
  1177.  
  1178. Basically, everything flows from the idea of this projection.
  1179.  
  1180. Reality strikes
  1181.  
  1182. In reality it is impossible to shoot enough projectors through
  1183. points to cover any area of the projection plane, no matter how
  1184. small. The compromise is to accept an error of about one pixel,
  1185. and shoot projectors only through pixels. This means you might
  1186. entirely miss things that project to something smaller than a
  1187. pixel, or incorrectly attrubute them a whole pixel. These
  1188. details become important in quality rendering. In that case,
  1189. steps have to be taken to ensure that sub-pixel details have
  1190. some form of impact on the global outlook of the image.
  1191. Different techniques can be used which will not be described
  1192. here.
  1193.  
  1194. Another thing we're going to do is only project the vertices of
  1195. lines and polygons and use the theorems we found earlier to
  1196. figure out the aspect of the projected object. For example, when
  1197. projecting a triangle, the projection is the triangle that
  1198. passes through the projection of the vertices of the unprojected
  1199. triangle. However, these projected vertices will very likely not
  1200. fall on integer pixel values. In this case, you have the choice
  1201. of either rounding or truncating to the nearest pixel, or taking
  1202. into account sub-pixel accuracy for vertices in your drawing
  1203. routine. The former can be easily done, the latter is a much
  1204. more involved topic which will not be discussed.
  1205.  
  1206. The state of things as they are at the moment of this writing
  1207. makes the texture mapping equations a bit too expensive at 2
  1208. divisions per pixel. On most processor today, division is
  1209. usually significantly slower than multiplication, and
  1210. multiplication itself is significantly slower than addition and
  1211. subtraction. This is expected to change in the near future
  1212. however. In the mean time, one can use interpolations instead of
  1213. exact calculations. These are discussed in the next section.
  1214.  
  1215. Interpolations and approximations
  1216.  
  1217. Introduction
  1218.  
  1219. Frequently in computer graphics, calculations require too much
  1220. processing power. When this problem arises, many solutions are
  1221. at hand. The most straightforward solution is to completely
  1222. forget about whatever causes the lengthy calculations. However,
  1223. that might not be satisfying. The second most straightforward
  1224. solution, in a certain sense, is to get faster hardware and
  1225. contend with slower image generation. That still might not be
  1226. satisfying. If this is the case, the only solution left to us is
  1227. to approximate.
  1228.  
  1229. Generally speaking, given a relatively smooth function of x over
  1230. a finite range, it is usually possible to approximate it with
  1231. another, easier to compute function over the same range. Of
  1232. course, this will generate some form of error. Ideally, we
  1233. should pick the approximating function as to minimize this error
  1234. while conforming to whatever constraints we may impose. However,
  1235. minimizing error is not always straightforward, and it is also
  1236. usually preferable to find a good approximating function quick
  1237. than the best approximating function after complicated
  1238. computations. (In the latter case, we might as well not
  1239. approximate.) Error computation is a rather complicated topic,
  1240. and I do not wish to get involved with it in here. For the more
  1241. formally oriented reader, one popular definition of error
  1242. between f(x) and g(x) is (f(x)-g(x))2dx, the integral is to be
  1243. taken over the interval over which g(x) is to approximate f(x).
  1244.  
  1245. One of the more popular type of approximating functions are
  1246. polynomials, mainly because they can usually be computed
  1247. incrementally in a very cheap and exact manner. Fourier series
  1248. are generally not useful because trigonometric functions cannot
  1249. be computed very quickly. A very nice way of generating an
  1250. approximating polynomial is to use the Taylor series of the
  1251. function we want to approximate, assuming we have an analytical
  1252. form of the said function.
  1253.  
  1254. Polynomials will be used to approximate everything from square
  1255. roots to texture mapping to curves.
  1256.  
  1257. Forward differencing
  1258.  
  1259. Forward differencing is used to evaluate a polynomial at regular
  1260. intervals. For example, given the polynomial y=a*x+b, which is a
  1261. line, one might want to evaluate it at every integer value of x
  1262. to draw a line on screen.
  1263.  
  1264. We must of course initially compute y(0)=a*0+b, or y(0)=b. But
  1265. then, we can exploit coherence. Coherence is something that
  1266. occurs just about everywhere in computer graphics, and
  1267. exploiting it can tremendeously cut down on the computations.
  1268.  
  1269. The next value we are interested in is y(1). But,
  1270. y(1)=y(0)+y(1)-y(0). (Notice that the y(0)'s cancel out).
  1271. However, y(1)-y(0)=a. Thus, y(1)=y(0)+a. Furthermore,
  1272. y(2)-y(1)=a, thus we can add a to y(1) to find y(2) and so on.
  1273. Generally speaking, y(n+1)-y(n)=[a*(n+1)+b]-[a*n+b]=a.
  1274.  
  1275. This extends to higher order polynomials. As an example, let's
  1276. do it on a second degree polynomial, and in a more formal
  1277. manner. We will suppose a step size of k instead of 1 for more
  1278. generality, and the following generic polynomial:
  1279.  
  1280. y=Ax2+Bx+C
  1281.  
  1282. First, let's find y(n+k)-y(n) as we did before:
  1283.  
  1284. y(n+1)-y(n)=[A(n+k)2+B(n+k)+C]-[An2+Bn+C]
  1285.  
  1286.     =[An2+2kAn+Ak2+Bn+kB+C]-[An2+Bn+C]
  1287.  
  1288.     =2kAn+Ak2+kB
  1289.  
  1290. Let's call that last result dy. Thus, y(n+1)=y(n)+dy(n). Now the
  1291. problem is evaluating dy(n). However, dy(x) is itself a
  1292. polynomial (first order; a line), so forward differencing can
  1293. also be applied to it. We thus need dy[n+1]-dy[n], which is
  1294. simply 2kA.
  1295.  
  1296. Concretely, this is what happens. Let's say we have the
  1297. polynomial x2+2x+3 with a step size of 4 over the range 3-19,
  1298. inclusively. We thus have A=1, B=2, C=3. We calculated dy(x) to
  1299. be 2kAx+Ak2+kB=2*4*1*x+1*42+4*2=8x+24.
  1300.  
  1301. First of all we calculate the initial values for y and dy, which
  1302. are y(3)=18 and dy(3)=48. The incremental value for dy is 2kA=8.
  1303. Then, we proceed as follows:
  1304.  
  1305. Value of...
  1306.  
  1307.     x    y(x)    dy(x)
  1308.  
  1309.     3    18    48
  1310.  
  1311. (as initially calculated - now add dy(x) to y(x), 8 to dy(x) and
  1312. 4 to x)
  1313.  
  1314.     7    66    56
  1315.  
  1316. (once more, add dy(x) to y(x) and 8 to dy(x) and 4 to x)
  1317.  
  1318.     11    122    64
  1319.  
  1320. (etc...)
  1321.  
  1322.     15    188    72
  1323.  
  1324.     19    260    80
  1325.  
  1326. These can be trivially extended to multi-variable polynomials.
  1327.  
  1328. Approximation function
  1329.  
  1330. Finding the approximation function is the real problem. When
  1331. trying to approximate a function, we usually want to minimize
  1332. error measure in some specific way. However, sometimes
  1333. additionnal contraints have to be taken into account. For
  1334. example, when interpolating values across polygons, care should
  1335. be taken that they are interpolated in a way that does not cause
  1336. too much contrast and/or mach banding along the edges shared by
  1337. more than one polygon.
  1338.  
  1339. One of the more obvious ways of generating an approximation
  1340. polynomial is to make a Taylor series expansion of whatever
  1341. function you want to approximate. This, however, does nothing
  1342. about the edge constraint we just mentionned. However, Taylor
  1343. series do just fine, for example, for normalizing vectors that
  1344. are supposed to be normal but due to error buildup aren't. The
  1345. problem with normalizing a vector is that vector (a,b,c) has a
  1346. norm of N=(a2+b2+c2)1/2, and that the normalization of (a,b,c)
  1347. is 1/N*(a,b,c). Usually, extracting a square root is very long,
  1348. and a division is also longer than a multiplication. It would be
  1349. nice if we could find an approximation of 1/sqrt(x) and multiply
  1350. by that instead. Actually, the two first terms of the Taylor
  1351. series expansion of 1/sqrt(x) about 1 are:
  1352.  
  1353. 1/sqrt(x)(3-x)/2 (around x1)
  1354.  
  1355. The division by two can be accomplished with a bit shift, and
  1356. subtraction is usually fairly fast on any CPU. Using x=a2+b2+c2,
  1357. we can find 1/sqrt(x) much faster than otherwise.
  1358.  
  1359.  
  1360.  
  1361. The picture above demonstrates what happens when one
  1362. approximates a value that varies smoothly across faces with a
  1363. Taylor series. The upper half of the picture shows a square for
  1364. which the intensity of a pixel (x,y) is 1/x. The leftmost pixels
  1365. have x=1 (intensity 1), and the rightmost pixels have x=3
  1366. (intensity 1/3). The lower half shows two Taylor approximations.
  1367. The first Taylor series expansion was done around x=1, the
  1368. Taylor polynomial is thus 4-6x+4x2-x3. This corresponds to the
  1369. lower left square. As can be seen, near the left edge, the
  1370. Taylor series is nearly perfect. Near x=2, though, it goes
  1371. haywire. The bottom right square is a Taylor series expansion
  1372. about x=2 (the polynomial is 2-3/2x+1/2x2-1/16x3). As can be
  1373. seen, it is much closer to the real thing, but that's only
  1374. because 1/x becomes more and more linear after that point. But
  1375. things that are linear after the perspective transform are the
  1376. exception rather than the rule.
  1377.  
  1378. The moral of this story is that if two faces are next to each
  1379. other, and that the shading (or any other property) is really a
  1380. continuous function, but we approximate it using Taylor series
  1381. about arbitrary points, it is very easy to get something that
  1382. does not look continuous at all.
  1383.  
  1384. Thus, it would be unwise to do a Taylor series expansion of
  1385. texture mapping equations, or Phong shading and the like. Note
  1386. that a property that varies with 1/x is not a rare thing in
  1387. computer graphics because of the perspective transform, thus the
  1388. example is very relevant.
  1389.  
  1390. Rendering
  1391.  
  1392. Introduction
  1393.  
  1394. Rendering is the phase where we do the actual drawing. There is
  1395. a general tendency to download this particular task to a slave
  1396. graphics processor and leave the CPU to do better things.
  1397. However, it will always be useful for everyone to have a general
  1398. understanding of how things work. And also likely is the fact
  1399. that we're going to need software renderers for a while more.
  1400. And one last fact is that people have to write the software for
  1401. the slave processor.
  1402.  
  1403. We will first study the drawing of a point, which will be used
  1404. to draw other primitives. Then we will study lines and polygons.
  1405. Curved surfaces can also be supported but will not be discussed.
  1406. The curved primitive that tend to be faster in drawing are
  1407. ellipses and polynomials. However, some other forms of curved
  1408. primitives definitions are often preferred, mainly splines.
  1409.  
  1410. The point
  1411.  
  1412. A geometric point is a 0 dimensional object. It could also be
  1413. defined very strictly with neighborhoods and somesuch. However,
  1414. this is not particularly useful to the computer graphics
  1415. specialist. One thing that we must remember, though, is that it
  1416. is impossible to display a point on any medium. Quite simply, a
  1417. point has a size of zero, no matter if the definition of size is
  1418. length, area or volume. It cannot be seen under any
  1419. magnification.
  1420.  
  1421. What the computer graphics expert usually refers to the point is
  1422. the smallest entity that can be displayed on the display device.
  1423. These are not necessarely circular or rectangular things - and
  1424. more often than not, they are slightly blurred.
  1425.  
  1426. We will refer to this point as a pixel. We will also need to
  1427. make a few basic assumptions. Generally speaking, pixels are of
  1428. an arbitrary shape (often rectangular-like), and are aligned in
  1429. a very structured way on the display device. Note that some
  1430. devices do not use this method of displaying things, these are
  1431. commonly referred to as vector devices. There was an old Star
  1432. Wars (trademark of LucasArts I beleive) game made with one of
  1433. these.
  1434.  
  1435. We will also very much like pixel to be aligned in a cartesian
  1436. plane like manner. We generally assign pixels integer position,
  1437. and what's not exactly on a pixel has a noninteger position. But
  1438. what is the position of the pixel? That's another entirely
  1439. arbitrary matter. Generally speaking, we might want to simplify
  1440. the pixel's location to its centroid. Also, there is the problem
  1441. of axis orientation. For a combination of arbitrary and
  1442. historical reasons, the screen coordinates origin is very
  1443. usually centered on the upper left corner and goes positively
  1444. down and right in hardware. Operating sometimes hide that from
  1445. the user application and use a coordinate system centered on the
  1446. lower left corner, and go positively up and right, just like the
  1447. usual cartesian plane.
  1448.  
  1449. The way that pixels are stored internally is also of importance.
  1450. Generally speaking, each pixel is assigned a color, and the
  1451. number of colors available per pixel is defined by the number of
  1452. bits allocated to each pixel. For instance, if each pixel has 6
  1453. bits of color data to it, then each pixel can be one of 64
  1454. colors. When an odd number of bits per pixel is used, it often
  1455. happens that the bits are spread in a less intuitive way. For
  1456. example, in the 6 bit case, instead of using one byte per pixel
  1457. and wasting 2 bits per pixel, the system will likely store bit 0
  1458. of all pixels, then bit 1 of all pixels, then bit 2 of all
  1459. pixels, and so on. This is called a bit-plane arrangement.
  1460.  
  1461. If the number of bits per pixel is closer to 8, 16, 24 or 32,
  1462. then some systems will allow what is generally referred to as a
  1463. linear arrangement of pixels. For example, if 8 bits are
  1464. allocated per pixel, then one byte corresponds to one pixel.
  1465.  
  1466. It is generally accepted that with 24 bits per pixel, the human
  1467. eye cannot see the difference between two very similar shades of
  1468. the same color. However, 24 bits per pixel is roughly 16
  1469. millions of colors. Thus, when using a mere 6 or 8 bits per
  1470. pixel, sacrifices must be made.
  1471.  
  1472. One way that the industry has found is to make a look-up table.
  1473. As an example, each pixel is assigned a value from 0 to 255 (for
  1474. 8 bits), and the hardware is given a lookup table of 256 color
  1475. entries. Each color entry can contain a 16 or 24 bit color for
  1476. example. Then, the hardware automatically substitute the proper
  1477. entry in the table for each pixel when it has to display them.
  1478. The lookup table is often referred to as the palette or color
  1479. map, the last term being slightly more appropriate in my opinion.
  1480.  
  1481. At any rate, eventually one needs a way of identifying colors,
  1482. either to select the color map colors, or in the case of a 24 or
  1483. 32 bits system, select the pixel color. There are several ways
  1484. of doing this. Two of the most popular means are RGB colors. RGB
  1485. is an acronym for red, green and blue. Colors are specified by
  1486. their red, green and blue contents. It is interesting to note
  1487. that displays usually do not use red, green and blue, but colors
  1488. that are close to these. The colors actually used by the
  1489. displays were selected to allow for a broader range of colors.
  1490.  
  1491. Another popular means of selecting a color is with HSV values.
  1492. This is another acronym that stands for Hue, Saturation and
  1493. Brightness (isn't that last one obvious?) This model is more
  1494. intuitive than the RGB model for most people. Other models
  1495. include the CMY (Cyan, Mangenta and Yellow) and YIQ (Luminance
  1496. and Chromaticity) models.
  1497.  
  1498. Writing to a specific pixels usually involves finding an address
  1499. and then putting a value in it. Since memory is usually mapped
  1500. in a one dimensional fashion, device pixels are mapped in an
  1501. arbitrary way to memory. Usually, finding a memory location for
  1502. a pixel involves a multiplication. However, multiplications are
  1503. typically expensive, thus we might want to look into that a bit
  1504. further. Let us assume a 1024x768 display, with 8 bits per pixel
  1505. and linear mapping.
  1506.  
  1507. A base address A has to be given for the top-leftmost pixel
  1508. (assuming origin is at top-left). Then, the first row of 768
  1509. pixels would be the next 768 bytes. Then next row of 768 pixels
  1510. would follow and so on. Generally speaking, pixel (x,y) for an
  1511. integer x and y can be found at memory location A+x+y*768. Note
  1512. that some systems will want to pad each row with a few bytes
  1513. sometimes.
  1514.  
  1515. Multiplying once per pixel write is a bit expensive. There are
  1516. several workarounds. The first one is straightforward but
  1517. hardware dependant. The second one assumes that we access pixels
  1518. in a coherent way (not totally random).
  1519.  
  1520. If the width of the display device in pixels is known in
  1521. advance, the multiplication can be removed the following way.
  1522. Say the pixel to be addressed is at memory location A+x+y*768.
  1523. 768 is 512+256, thus we have A+x+y(512+256) = A+x+512y+256y.
  1524. However, 512=29 and 256=28. Thus, the pixel memory location is
  1525. A+x+29y+28y. Note that a multiplication by a power of two can be
  1526. optimized out with left shifts, which are typically much faster
  1527. than multiplications. Let a<<b denote a shifted left by b bits,
  1528. then the memory location of the pixel can be expressed as:
  1529.  
  1530. A+x+y<<9+y<<8.
  1531.  
  1532. Similar decompositions in powers of two of various scalars can
  1533. be found. The problem with this is that it requires the scalar
  1534. (display device width in pixels) to be hard-coded in the program.
  1535.  
  1536. Another way of accessing pixels is by exploiting coherence. If
  1537. we plane to access all the pixels on a given scanline, starting
  1538. from left to right, then the following is true.
  1539.  
  1540. Pixel at memory location A+y*width is the leftmost pixel on the
  1541. scanline. The second leftmost value is the above value plus one.
  1542. The third one can be found by adding one again, and so forth.
  1543. Thus, accessing pixels that are adjacent on a scanline can be
  1544. done in one add per pixel only.
  1545.  
  1546. Accessing pixels that are on the same column is similar, except
  1547. that <width> is added each time to the memory location.
  1548.  
  1549. Lines
  1550.  
  1551. There are a number of ways to draw lines. Generally, they all
  1552. boil down to the same basic ideas, and have roughly comparable
  1553. speeds. The algorithm presented here is the one I felt had the
  1554. best mixture of simplicity, efficiency and small size. It has
  1555. the disadvantage of being less exact than some other algorithms
  1556. for lines of rational slopes. We will first start with special
  1557. cases, then move to more general cases.
  1558.  
  1559. The simplest lines to draw are the horizontal and vertical ones.
  1560. As can be imagined easily by the reader from the last section,
  1561. we start with the topmost or leftmost pixel, draw it, then
  1562. either add 1 or <width> to memory location and draw the next
  1563. pixel. And so on, for the length of the line.
  1564.  
  1565. The next step up is an angled line. If the line is not vertical
  1566. nor horizontal, then it can be expressed as y=mx+b or x=ny+c,
  1567. with n=1/m and c=-b/m, whichever is preferred. The
  1568. representation one has to use is whichever of the two has the
  1569. smallest m or n. This is to ensure that there are no large gaps
  1570. between the pixels of a line. Afterwards, we initialize (x0,y0)
  1571. to be one endpoint of the line. If we chose y=mx+b, we should be
  1572. using the leftmost endpoint for (x0,y0). We draw (x0,y0), then
  1573. increment x, and add m to y. Then we draw the new point. The
  1574. extension to the x=ny+c form is left to the reader.
  1575.  
  1576. Notice that the previous paragraph is simply an application of
  1577. forward differencing studied previously. The witty reader will
  1578. easily imagine the extension of this to higher degree
  1579. polynomials. It is also possible to extend incremental
  1580. algorithms to circles and ellipses, amongst others, but we will
  1581. not go into this.
  1582.  
  1583. In some applications, such as polygon drawing, one of either
  1584. y=mx+b or x=ny+c will be prefered even if the slope is greater
  1585. than 1.
  1586.  
  1587. Note that the topic of line drawing can be extended much more
  1588. than this. Anti-aliased lines, line width and patterns, endpoint
  1589. shape are all topics that we will not cover.
  1590.  
  1591. Polygon drawing
  1592.  
  1593.  
  1594.  
  1595. Let us first define a few terms, in an intuitive and geometric
  1596. fashion. A polygon is, as can be seen above, a 2d object with
  1597. area, delimited by edges. The edges are line segments, and there
  1598. is a finite number of edges.
  1599.  
  1600. Polygons that do not self-intersect can be said to be either
  1601. convex or concave. The polygon above is self-intersecting. A
  1602. convex polygon is one for which the inside angle at any vertex
  1603. is less than or equal to 180 degrees. All other polygons are
  1604. said to be concave. Sometimes, it is said that a particular
  1605. vertex is concave, which is not entirely correct, but rather
  1606. means that the inside angle at that vertex is more than 180
  1607. degrees.
  1608.  
  1609. What interests us most is filled primitive. It is relatively
  1610. easy to draw a wire frame polygon using only line drawing
  1611. routines described previously (hidden line removal then becomes
  1612. a problem).
  1613.  
  1614. The star-shaped polygon shown above is very interesting to us
  1615. because it exhibits the more interesting properties we want our
  1616. polygons to have. The grayed areas are considered to be inside
  1617. the polygon, where the white areas are outside the polygon. This
  1618. means that the inner pentagon is considered to be outside. The
  1619. rule for determining whether a point lies inside or outside the
  1620. polygon is as follows.
  1621.  
  1622. To determine if a point lies in or out of a polygon, draw a line
  1623. from that point to infinity (any direction, far far away). Now
  1624. find the number of times that line intersects the polygon edges.
  1625. If it is odd, the point is in, if it is even, the point is out.
  1626. It is recommended that you try this with the star above and that
  1627. it works no matter what point you pick and no matter what
  1628. direction you draw the line in.
  1629.  
  1630. The basic idea of the line polygon drawing algorithm is as
  1631. follows. For each scanline (horizontal line on the screen), find
  1632. the points of intersection with the edges of the polygon,
  1633. labeling them 1 through n for n intersections (it is of note
  1634. that n will always be even except in degenerate cases). Then,
  1635. draw a horizontal line between intersections 1 and 2, 3 and 4, 5
  1636. and 6, ..., n-1 and n. Do this for all scanlines and you are
  1637. done.
  1638.  
  1639. Probably, you might want to restrict yourself to scanlines that
  1640. are actually spanned by the polygon. Also, there are a few
  1641. things to note.
  1642.  
  1643. If the polygon is convex, there will always be only one span per
  1644. scanline. That is generally not true for concave polygons
  1645. (though it can accidentally happen).
  1646.  
  1647. Here is pseudocode for a polygon filling algorithm.
  1648.  
  1649.  
  1650.  
  1651. Let an edge be denoted (x0,y0)-(x1,y1), where y0y1. Edges also
  1652. have a "current x" value, denoted cx. Initialize cx to x0. One
  1653. should also compute the slope of all edges, denoted s, which is
  1654. (x1-x0)/(y1-y0) (we are using the x=ny+c representation).
  1655.  
  1656. Let IET be the inactive edge table, initially containing all
  1657. edges
  1658.  
  1659. Let AET be the active edge table, initially empty
  1660.  
  1661.  
  1662.  
  1663. Sort the IET's edges by increasing values of y0
  1664.  
  1665. Let the initial scanline number be the y0 of the first edge in
  1666. the IET
  1667.  
  1668.  
  1669.  
  1670. Repeat
  1671.  
  1672. While scanliney0 of the topmost edge in the IET
  1673.  
  1674. Move topmost edge from IET to AET
  1675.  
  1676. End while
  1677.  
  1678.  
  1679.  
  1680. (*)    Sort AET in increasing values of cx
  1681.  
  1682.  
  1683.  
  1684. For every edge in the AET
  1685.  
  1686. If edge's y1scanline, then remove edge from AET
  1687.  
  1688. Else add the slope "s" to "cx".
  1689.  
  1690. End for
  1691.  
  1692.  
  1693.  
  1694. For each pair of edge in the AET
  1695.  
  1696. Draw a horizontal segment on current scanline between column
  1697. "cx0" and "cx1", where "cx0" is the "cx" value for the first
  1698. edge in the pair and "cx1" is the "cx" value for the second edge
  1699. in the pair
  1700.  
  1701. End for
  1702.  
  1703. Until the AET is emtpy
  1704.  
  1705. It is of note that the line marked by (*) can be optimized out.
  1706. If the polygon is not self-intersecting, we just need to make
  1707. sure the AET is properly sorted when we insert a new edge into
  1708. it.
  1709.  
  1710. It should be noted that edges that are parallel to the scanline
  1711. should not be put in the IET. You might also need to clip the
  1712. polygon to the viewport, which can be added to the polygon
  1713. blitting code.
  1714.  
  1715. Visible surface determination
  1716.  
  1717. Introduction
  1718.  
  1719. One of the problems we have yet to address, when several objects
  1720. project to the same area on screen, how do you decide which gets
  1721. displayed. Intuitively, the closest object should be the one to
  1722. be displayed. Unfortunately, this definition is very hard to
  1723. handle. We will usually say that the object to be displayed will
  1724. be the one with the smallest z value in eye space, which is a
  1725. bit easier to work with. A corollary of this is that objects
  1726. with the largest 1/z value get displayed, this latter
  1727. observation has applications which will be explained later.
  1728.  
  1729. Visible surface determination can be done in a number of ways,
  1730. each has its advantages, disadvantages and applications. Hidden
  1731. line removal is used when wire frames are generated. This might
  1732. be useful for a vector display, but will not be covered in here.
  1733. When dealing with filled primitives, there are several classes
  1734. of visible surface determination. There is also the question of
  1735. object precision, device precision, and more, these topics will
  1736. not be discussed here.
  1737.  
  1738. Perhaps the most intuitive visible surface determination
  1739. algorithm is the so-called "painter's algorithm", which works
  1740. the same way a painter does. Namely, it draws objects that are
  1741. further away first, then draws objects that are closer. The
  1742. advantage of this is it's simple. The disadvantages are that it
  1743. writes several times to some areas of the display device, and
  1744. also that some objects cannot be ordered correctly.
  1745.  
  1746. The painter's algorithm can be generalized into the
  1747. depth-sorting algorithm, which sort the primitives from back to
  1748. front and then draw. The depth sorting algorithm also resolves
  1749. cases that painter's algorithm does not.
  1750.  
  1751. Another algorithm is space partitioning trees such as BSP
  1752. (binary space partitions) trees. The advantage of this algorithm
  1753. is to generate a correct ordering of the primitives quickly and
  1754. correctly no matter where the viewer is. The disadvantage is
  1755. that the object has to be static (e.g. no stretching), but still
  1756. can move and rotate in space. It is also quite hard to merge two
  1757. BSP trees together. Approximations can be made.
  1758.  
  1759. Yet another way of doing visible surface determination is the
  1760. class of algorithms generally referred to as "scan-line
  1761. algorithms". These algorithms, though somewhat slower than depth
  1762. sorting, have the advantage of drawing to each and every pixel
  1763. of the display device once and only once. Thus there is no need
  1764. to clear the display in the first place, and pixels are not
  1765. written to needlessly. Incidentally, this algorithm is very
  1766. useful for display devices where it is impossible or difficult
  1767. to erase or rewrite to pixels, such as printers. The
  1768. disadvantages are that it's slightly slower, and usually quite
  1769. more messy to code than a depth sorting algorithm. Also, visible
  1770. surface determination becomes an integral part of the polygon
  1771. drawing routine in most cases, making it hard to download the
  1772. polygon drawing code to some hardware, or to make several
  1773. versions of polygon drawing code for different drawing modes.
  1774.  
  1775. A very popular way of doing visible surface determination is
  1776. called z-buffering. This works by storing the z value whatever
  1777. occupies a pixel for each pixel. This way, one can add new
  1778. primitives to a scene, visible surface determination is just a
  1779. compare away. Incidentally, it is usually much more efficient to
  1780. use 1/z values than it is to use z values, since 1/z varies
  1781. linearly but z does not.
  1782.  
  1783. Another algorithm worth mentioning is the Weiler-Atherton
  1784. algorithm, which clips primitives so that they do not intersect
  1785. before drawing, and Warnock's algorithm, which recursively
  1786. subdivides the display area until it can trivially determine
  1787. which primitive to draw. These algorithm are fairly slow.
  1788.  
  1789. An optimization that can be made to any visible surface
  1790. determination algorithm is back-face removal or back-face
  1791. culling. This is based on the observation that faces that are
  1792. facing away from the observer
  1793.  
  1794. As of now, the only algorithms discussed will be the depth sort
  1795. and painter's algorithm, along with z buffering and back-face
  1796. culling.
  1797.  
  1798. Back-face culling
  1799.  
  1800. Back-face culling exploits the observation that a face in a
  1801. closed polyhedron always has two sides. One faces inside, and
  1802. can never be seen by an observer outside the polyhedron (rather
  1803. obviously since the polyhedron is closed), the other faces
  1804. outside and can be seen. However, if it is determined that the
  1805. side facing the eye is the inside of the face, that face will
  1806. assuredly not be seen, because it is impossible to see a face
  1807. from the inside.
  1808.  
  1809. The side that faces the eye can be determined easily with dot
  1810. product. Take a vector V from the eye to any point withing the
  1811. polygon (for example, from the eye to a vertex). Let A be the
  1812. normal of the polygon, assuming that A points outwards of the
  1813. polyhedron. Then, compute VA. If it is positive, the inside of
  1814. the face is towards the camera, do not display or transform the
  1815. face. If it is negative, the face is facing the camera and might
  1816. be seen (though this is not guaranteed).
  1817.  
  1818. Back-face culling is generally not sufficient for visible
  1819. surface determination. It is merely used to remove faces that
  1820. assuredly cannot be seen. However, it will do nothing for faces
  1821. that are only obscured by faces that are closer. Also, back-face
  1822. removal assumes that the objects are closed polyhedra, and that
  1823. faces are opaque. If this is not the case, back-face culling can
  1824. not be applied.
  1825.  
  1826. Note that if the only thing displayed is a convex object,
  1827. back-face culling is sufficient for visible surface
  1828. determination (it will only leave the faces that are actually
  1829. visible).
  1830.  
  1831. Also note that back-face removal should be done in object space,
  1832. not in world or eye space. That's because, in order to do it in
  1833. world space, one has to transform all plane normals before doing
  1834. the dot product, which is rather expensive. However, if
  1835. performing the culling in object space, one only needs the
  1836. location of the eye in object space, and normals need not be
  1837. transformed.
  1838.  
  1839. It can be shown that back-face culling is expected to cull
  1840. roughly half of the number of vertices, faces and edges in a
  1841. scene, except for special scenes that are made to be viewed from
  1842. a particular angle or somesuch.
  1843.  
  1844. Sorting
  1845.  
  1846. With the painter's algorithm, one has to assign a z-value to all
  1847. primitives. Then, the primitives are sorted according these
  1848. values of z, and the resulting image is drawn back-to-front.
  1849. Several sorting algorithms can be used for this purpose, and
  1850. even though basic algorithmics is not the purpose of this
  1851. document, we will discuss two simple sorting schemes now.
  1852.  
  1853. The simplest sorting algorithm, and a frightfully slow algorithm
  1854. in most cases, is the bubble sort. Here follows pseudocode for
  1855. the bubble sort.
  1856.  
  1857.  
  1858.  
  1859. Let z[1..n] be the array of n values to sort
  1860.  
  1861. Let f be a flag
  1862.  
  1863.  
  1864.  
  1865. Repeat
  1866.  
  1867.     Clear f
  1868.  
  1869. For i varying from 1 to n-1
  1870.  
  1871. If z[i]>z[i+1] then
  1872.  
  1873. Set f
  1874.  
  1875. Exchange z[i] and z[i+1]
  1876.  
  1877. End if
  1878.  
  1879. End for
  1880.  
  1881. Until f is clear
  1882.  
  1883. As can be seen, the algorithm is exceedingly simple. For small
  1884. values of n (say, n<10), this algorithm can be used and will be
  1885. close to optimal. However, if the list is very badly ordered
  1886. initially, the sort could take up to n2 iterations before
  1887. finishing.
  1888.  
  1889. Small improvements can be made to the algorithm. For one thing,
  1890. instead of always scanning in the same direction (from the first
  1891. element to the last), one alternates directions, sorting an
  1892. already close to sorted list is very efficient. The loop will
  1893. execute roughly n times (actually, it would execute k times n,
  1894. where k is some small constant). In the worse case though, it
  1895. still executes in n2 iterations.
  1896.  
  1897. A second, more clever algorithm that works well on numbers, is
  1898. the bucket sort, or radix sort. This sort can be done in any
  1899. base (useful bases for a computer would be 2, 16 or 256, because
  1900. they're powers of two). However, for the sake of simplicity in
  1901. this example, we will use base 10.
  1902.  
  1903. Using base n, n buckets are created (in our example, 10
  1904. buckets), labeled 0 through n-1 (0-9 in our example). Then, the
  1905. numbers to be sorted are put in the bucket that corresponds to
  1906. their lower digit. The buckets are concatenated, and the step is
  1907. repeated for the next lower digit. An so on, until we get to the
  1908. highest digit, at which point we stop. The result is a sorted
  1909. list. Pseudocode is given below for base n. Note that the ith
  1910. digit of base n number z is (z div ni)%n where div stands for
  1911. integer division, truncating off any fractions, and % is the
  1912. modulo operator, or remainder after division by n (a value from
  1913. 0 to n-1 inclusive).
  1914.  
  1915.  
  1916.  
  1917. Let b[0..n-1] be n buckets, labeled 0 through n-1
  1918.  
  1919. Let z[1..m] be the m numbers to sort
  1920.  
  1921. Let D be the largest number of digits used
  1922.  
  1923.  
  1924.  
  1925. For foo varying from 0 to D-1 inclusive, do
  1926.  
  1927. For i varying from 1 to m inclusive, do
  1928.  
  1929. Put z[i] into its bucket, namely b[(z[i]/nfoo)%n]
  1930.  
  1931. End for
  1932.  
  1933. Concatenate all buckets, in order from 0 to n-1, back into z
  1934.  
  1935. End for
  1936.  
  1937. Note that division and modulo operations, when done with base
  1938. two divisors, can be implemented strictly with bit shifts.
  1939.  
  1940. This algorithm can be implemented with lists or arrays. Lists
  1941. ensure that no unnecessary copying is done, and allow buckets to
  1942. grow dynamically. This is not so easily accomplished with
  1943. arrays, but the pseudocode below essentially does that. It only
  1944. needs to be repeated for every byte in the numbers to be sorted.
  1945.  
  1946.  
  1947.  
  1948. Let i[0..256] be 257 indices, initialized to 0
  1949.  
  1950. Let z[1..m] be the m numbers to sort
  1951.  
  1952. Then o[1..m] will be the m numbers once concatenated
  1953.  
  1954.  
  1955.  
  1956. Comment: The first step we take is to count the elements that
  1957. will go into each bucket
  1958.  
  1959.  
  1960.  
  1961. For j varying from 1 to m inclusive, do
  1962.  
  1963. Let foo be the bucket to which z[j] belongs
  1964.  
  1965. Increment i[foo]
  1966.  
  1967. End for
  1968.  
  1969.  
  1970.  
  1971. Comment: now compute the index at which buckets start
  1972.  
  1973.  
  1974.  
  1975. For j varying from 1 to 255 inclusive, do
  1976.  
  1977. Add i[j-1] to i[j]
  1978.  
  1979. End for
  1980.  
  1981.  
  1982.  
  1983. Comment: lastly, put the numbers into the bucket and concatenate
  1984.  
  1985.  
  1986.  
  1987. For j varying from 1 to m inclusive, do
  1988.  
  1989. Let foo be the bucket to which z[j] belongs
  1990.  
  1991. Put z[j] into o[i[foo]]
  1992.  
  1993. Increment i[foo]
  1994.  
  1995. End for
  1996.  
  1997. Other sorting algorithms that might be of interest are the quick
  1998. sort, heap sort and insertion sort. These will not be discussed
  1999. here, they each have their advantages and drawbacks.
  2000.  
  2001. Painter's algorithm and depth sorting
  2002.  
  2003. As was previously mentionned, painter's algorithm assigns a z
  2004. value to each primitive, then sorts them, then draws them from
  2005. back to front. Objects that lie behind are then written over by
  2006. objects that lie in front of them. Note that, no matter the
  2007. scheme used to select the z value for an object, primitives that
  2008. have overlap in z may be incorrectly ordered. But there is
  2009. worse. Note the pathological case below, where it is impossible
  2010. to generate a proper ordering for the three triangles:
  2011.  
  2012.  
  2013.  
  2014. In this case, it is necessary to cut one triangle into two parts
  2015. and sort the parts individually.
  2016.  
  2017. A way of handling all cases is as follows. Assign a z value to
  2018. all polygons equal to the vertex belonging to the polygon that
  2019. has the largest z coordinate value in eye space. Then sort as
  2020. per painter's algorithm. Before actually drawing, we need to do
  2021. a postsort stage to make sure the ordering is correct for
  2022. polygons that have z overlap.
  2023.  
  2024. Assuming we sorted in increasing values of z, it means that we
  2025. need only to compare the last polygon with the consecutive
  2026. previous polygons for which the furthest point is in the last
  2027. polygon's z span. Once the last polygon is processed, we will
  2028. not touch it anymore (unless the last polygon is moved to some
  2029. other position in the list). Thus, we just consider the list to
  2030. be one element shorter and recurse the algorithm.
  2031.  
  2032. The steps that should be taken are as follow (P and Q are the
  2033. polygons we are comparing).
  2034.  
  2035. 1- Check wether the polygons x and y extent overlap on screen.
  2036. If they do not, there is no need to compare the polygons.
  2037. Otherwise, we are undecided (go to 2)
  2038.  
  2039. 2- Check on what side of P's plane the eye lies. If Q lies
  2040. entirely on that side of P's plane, Q is considered to be in
  2041. front of P. If Q lies entirely on the opposite side of the eye
  2042. in relation to P's plane, then P is in front of Q. If Q crosses
  2043. P's plane, we are still undecided.
  2044.  
  2045. 3- Repeat 2 above, but with Q and P inverted.
  2046.  
  2047. 4- Check if the polygons overlap on screen (find wether the
  2048. edges of the polygons intersect)
  2049.  
  2050. Once a polygon has been moved in the list, mark it so that it is
  2051. not moved again. If one of the above steps would say that a
  2052. polygon that has already been moved in the list should be moved
  2053. again, then you will have to use the last resort, clipping.
  2054.  
  2055. Of course, one needs not to perform all these tests if they are
  2056. deemed to be more expensive than clipping. For instance, the
  2057. only tests one could do is test for overlap in z, then x and y
  2058. on screen, then check for step 2 and if it is still unresolved,
  2059. simply clip the polygons and put the pieces where they belong.
  2060.  
  2061. When polygon ordering can not be resolved, pick one of the two
  2062. polygons for clipping plane and clip the other polygon with it.
  2063. Then, insert the two pieces at the appropriate positions in the
  2064. list.
  2065.  
  2066. A very nice way of doing all these tests is as follows.
  2067. Calculate bounding boxes for z value in 3d, and u,v in 2d
  2068. (screen space, after perspective transform) of the polygon.
  2069. Then, sort the bounding boxes in x, u and v. This can be done in
  2070. linear time using the radix sort algorithm (or by exploiting
  2071. coherence in a comparison sort algorithm). Then, only the
  2072. polygons for which the bounding boxes overlap in all three axis
  2073. need to be checked further.
  2074.  
  2075. Z-Buffering
  2076.  
  2077. This algorithm tends to be slightly slower than painter's
  2078. algorithm for low number of polygons (less than 5000). It would
  2079. appear that it would gain as the numer of polygons increases
  2080. though.
  2081.  
  2082. The idea is to make an array of z or 1/z values, one for each
  2083. pixel. As you draw a polygon, compute the z or 1/z value at a
  2084. pixel, compare it with the current value for the pixel, and if
  2085. closer, draw, otherwise, do not draw.
  2086.  
  2087. This algorithm has the advantage that it requires no sorting
  2088. whatsoever. However, the algorithm performs one comparison per
  2089. pixel, which tends to be a bit expensive. Also, memory
  2090. requirements tend to be bigger than other algorithms.
  2091. Nevertheless, the simplicity of the implementation makes it very
  2092. attractive.
  2093.  
  2094. As a side note on evaluating z or 1/z, the latter can be shown
  2095. to be linear while the former is not. Thus, it will likely be
  2096. preferable to store 1/z values instead of z, because they can
  2097. typically be computed much more quickly. The mathematics of that
  2098. are shown below.
  2099.  
  2100. Let Ax+By+Cz=D be the plane equation for the polygon in eye
  2101. space. Let (u,v) denote the pixel on screen, and let the
  2102. perspective projection equation be u=px/z and v=qy/z for some
  2103. constants p and q. This can be rewritten as:
  2104.  
  2105. x=uz/p        y=vz/q
  2106.  
  2107. Auz/p+Bvz/q+Cz=D
  2108.  
  2109. z(Au/p+Bv/q+C)=D
  2110.  
  2111. And then, depending wether we are interested in z or 1/z, we get:
  2112.  
  2113. z=D/(Au/p+Bv/q+C)
  2114.  
  2115. or
  2116.  
  2117. 1/z=A/(Dp)u+B/(Dq)v+C/D
  2118.  
  2119. The latter can be rewritten as
  2120.  
  2121. 1/z=Mu+Nv+K
  2122.  
  2123. M=A/(Dp),    N=B/(Dq),    K=C/D
  2124.  
  2125. Thus, 1/z varies linearly across the (u,v) plane of the display
  2126. device. When forward differencing is applied, calculations for
  2127. values of 1/z are reduced to one add per pixel, with a small
  2128. setup cost.
  2129.  
  2130. Lighting models
  2131.  
  2132. Introduction
  2133.  
  2134. After all we have covered, we still have to decide how much
  2135. light gets reflected off things and such, and how it gets
  2136. reflected. For example, some objects that are facing towards a
  2137. light source will appear much more bright, perhaps with a very
  2138. brilliant spot somewhere, than objects facing away from it.
  2139. Objects also cast shadows, which are much harder to compute. We
  2140. might also want to somehow take into account that a certain
  2141. quantity of light bounces off everything and lights up things
  2142. equally from all directions.
  2143.  
  2144. Furthermore, we might want to vary the intensity of light across
  2145. a given polygon, especially if these polygons are big. If not,
  2146. one gets a somewhat ugly effect called mach banding where the
  2147. contrast between faces gets amplified by our brains. This will
  2148. raise the question of how the light should vary across a
  2149. polygon, and why.
  2150.  
  2151. The first part discusses actual lighting models, and the second
  2152. discusses shading algorithms for rasterization of nonuniformly
  2153. shaded polygons.
  2154.  
  2155. Lighting models
  2156.  
  2157. The most basic idea we can have is to make light intensity a
  2158. function of the angle between the direction of the light rays
  2159. from the light source to a point, and the normal to the point.
  2160. This is called diffuse lighting. This means that light reflects
  2161. off the face equally in all directions, so the direction in
  2162. which the eye is is not relevant.
  2163.  
  2164. Looking back on the vector algebra chapter, we had a definition
  2165. of angle with the dot product. This is written as:
  2166.  
  2167. Cos=AB/(|A||B|)
  2168.  
  2169. If A is the plane normal (of unit length), then |A| is 1 and can
  2170. be removed from the equation. B would be the vector from light
  2171. source to point to be lit. Then, we make light intensity a
  2172. function of Cos, which is calculated to be AB/|B|, which is
  2173. fairly easy to calculate. Note that if  is less than /2, it
  2174. means that the face is actually facing away from the light
  2175. source, in which case it should not receive any light from that
  2176. light source. This can be recognized when AB/|B|>0.
  2177.  
  2178. Usually, one makes the intensity of the light received from a
  2179. light source AB/|B| times some negative constant (since positive
  2180. values of AB/|B| mean that the face is facing away and that
  2181. intensity is then 0).
  2182.  
  2183. One might want to take into account the fact that light usually
  2184. diminishes the further away you are from a light source. Physics
  2185. say that light intensity is inversely proportional to the square
  2186. of the distance to the light source. This can be written as
  2187. k/|B|2, and multiplying that by the value previously given:
  2188.  
  2189. I=kAB/|B|3
  2190.  
  2191. However, as experimentation shows, it is sometimes useful to use
  2192. some other falloff than square of distance. Generally, people
  2193. have been using a second degree polynomial of |B|. However, if
  2194. we try the specific case of linear falloff, we get this very
  2195. interesting simplification:
  2196.  
  2197. I=kAB/|B|2
  2198.  
  2199. If B=(a,b,c), then |B|=(a2+b2+c2)1/2. Thus, |B|2=a2+b2+c2, which
  2200. eliminates the square root, which is usually the most expensive
  2201. calculation we have.
  2202.  
  2203. The question of what point on the polygon should be used for
  2204. calculating the vector B from light source to the point on the
  2205. polygon is answered as follows. Theoritically, B should be
  2206. recalculated for each point on the polygon. This might turn out
  2207. to be expensive, and a constant B is then used across the
  2208. polygon. In this case, however, the B/|B|2 factor should be
  2209. calculated only once for the whole polygon.
  2210.  
  2211. The Phong illumination model also includes a specular component.
  2212. In that case, a function of the angle between the ideal
  2213. reflection vector and the eye-to-point vector is added.
  2214.  
  2215. These calculations are done on a per light source basis, and
  2216. should be summed. Ambient light can also be added.
  2217.  
  2218. Shadow casting involves more complex calculations which will not
  2219. be discussed here.
  2220.  
  2221. Smooth shading
  2222.  
  2223. The simplest form of polygon shading calculates one value of
  2224. intensity and uses that value across the whole polygon.
  2225.  
  2226. The other forms of shading require that we first examine our
  2227. polyhedral model of objects. The assumption we are making is
  2228. that the polyhedral model is really an approximation to a curved
  2229. object. Thus, we would like the normal vectors and the shading
  2230. intensitites to vary smoothly across the surface of the objects,
  2231. just as it does on a curved surface.
  2232.  
  2233. The usual way of accomplishing this is by computing a pseudo
  2234. normal vector at each vertex. (Keep in mind that a point in 3d
  2235. has no normal vector, ergo we call it pseudo-normal.) That
  2236. pseudo-normal per vertex is not the normal of the vertex, but
  2237. rather the normal we think represents best the curved surface at
  2238. that point. If we have actual information about the curved
  2239. surface, we should use that information if we can to compute the
  2240. pseudo-normal. Otherwise, one good way of doing this is by
  2241. computing the weighted sum of the faces that touch the vertex.
  2242. For example, you could sum all normals of the faces that touch
  2243. the vertex and then normalize. Or, you could make each face's
  2244. contribution to the pseudo-normal a function of the face's area
  2245. or the angle made by that face at the vertex, and so on. For
  2246. ease in calculations, pseudo-normals should be made unit in
  2247. length.
  2248.  
  2249. Then, one can go either one of two ways. The first one is
  2250. interpolated shading, or Gouraud shading. The second one is
  2251. Phong shading, which is a bit more complex.
  2252.  
  2253. In Gouraud shading, one calculates the intensity of reflected
  2254. light on the vertices. Then, we linearly interpolate the
  2255. intensity of the light across the polygon, as shown below. Note
  2256. that for a n-gon, with n>3, gouraud shading is ambiguous in the
  2257. sense that it depends on scanline orientation. However, with
  2258. n=3, the shading is unambiguous. As a matter of fact, given a
  2259. triangle (x0,y0), (x1,y1) and (x2,y2) and the three intensities
  2260. at the points, respectively i0, i1, i2, we can view this as
  2261. three points in 3d (x0,y0,i0), (x1,y1,i1), (x2,y2,i2). Since we
  2262. are linearly interpolating, and that we have 3 points, then
  2263. there is only one solution, of the form i=Ax+By+C. Using matrix
  2264. mathematics, one can find the coefficients A, B and C, and then
  2265. computations are reduced to one add per pixel with very little
  2266. setup.
  2267.  
  2268.  
  2269.  
  2270. As can be seen above, intensities are calculated for all
  2271. vertices, particularly vertices a, b and c. Then, intensity is
  2272. linearly inerpolated between a and b (assuming m is 1/5 of the
  2273. way between a and b, we'll assign m an intensity of 4/5a+1/5b).
  2274. It is also interpolate linearly between a and c. Then, given the
  2275. light intensities at m and n, the intensity is interpolated
  2276. linearly between m and n. Assuming P is midway between these
  2277. two, then its intensity should be (m+n)/2.
  2278.  
  2279. It is easy to demonstrate that no point within the polygon will
  2280. be brighter or darker than the brightest or darkest vertex,
  2281. respectively. If a specular highlight should fall within a
  2282. polygon, Gouraud shading will miss it entirely.
  2283.  
  2284. Phong shading works around this the following way. Instead of
  2285. interpolating the intensity linearly, it interpolates the
  2286. (x,y,z) values of the pseudo-normals linearly, then normalizes,
  2287. and the does the lighting calculations once per pixel.
  2288.  
  2289. As you might imagine, this is extremely expensive. Many
  2290. approximations, workarounds and somesuch have been devised. Here
  2291. we will study one such approximation.
  2292.  
  2293. We will interpolate the (x,y) value of pseudo-normals linearly,
  2294. but we will set z=(1-x2-y2)1/2. Note that we still have a square
  2295. root. However, since z is a function of x and y only, and that x
  2296. and y vary between -1 and +1 only, we can make a lookup table
  2297. for z, which makes it a lot faster. Then we can do the lighting
  2298. calculations. However, this is still a bit slow. If we know our
  2299. light vector to be constant across the screen, then we can
  2300. optimize it further.
  2301.  
  2302. Assuming the light vector is (0,0,1), then the lighting
  2303. calculations for diffuse shading only is (x,y,z)(0,0,1). This
  2304. simplifies to z, which is (1-x2-y2)1/2, which is the value we
  2305. stored in the lookup table. So, interpolate (x,y) linearly and
  2306. lookup intensity in the lookup table. As a matter of fact, one
  2307. can even put some other values than (1-x2-y2)1/2 in the lookup
  2308. table. These can be used to achieve specular highlights,
  2309. multiple light sources, or even a nice reflection effect.
  2310.  
  2311. Computer graphics related problems
  2312.  
  2313. Introduction
  2314.  
  2315. In the process of learning computer graphics, one comes across
  2316. several of the classical questions in one version or another.
  2317. These include "how do I compute the plane normal of a triangle"
  2318. or more generally "how do I compute the plane normal of a
  2319. polygon, preferably using all vertices to minimize error", "how
  2320. do I make a normal that points outwards" and such.
  2321.  
  2322. These technical questions need to be addressed individually,
  2323. since they typically have very little in common. First will be
  2324. covered generating normals that point outwards for polygons. An
  2325. application of that will be covered, which is triangulation of a
  2326. concave polygon. Computation of a normal for any polygon is then
  2327. considered, by using all vertices to compute it. Then will be
  2328. covered the problem of generating plane normals that point
  2329. outwards of a polyhedron, which relies on edge normals that
  2330. point outwards of a polygon.
  2331.  
  2332. It is of note that the problem of convex decomposition of a
  2333. concave polyhedron, which has applications in various fields (3d
  2334. collision detection and visible surface determination) amongst
  2335. others, is a very complex problem (it has been demonstrated to
  2336. be NP-Complete) which will not be described herein.
  2337.  
  2338. Generating edge normals
  2339.  
  2340. It will prove to be essential for the later problems to have
  2341. normals for the edges that point outwards from the polygon. We
  2342. might as well start by saying that for an edge of slope m, the
  2343. normal would be (-m,1) unitized. The second preliminary is
  2344. defining modulo space addition and subtraction.
  2345.  
  2346. Let a and b be integers of modulo n space. Then, ab is defined
  2347. to be (a+b)%n, where x%y means "remainder of the division of x
  2348. by y" (the remainder is always positive, between 0 and y-1).
  2349. Similarly, ab is defined to be (a-b)%n. As an example, let's
  2350. assume we are working in modulo 8 space. Then,
  2351.  
  2352. 32=5%8=5        56=11%8=3        43=1%8=1        47=-3%8=5
  2353.  
  2354. The first step is to generate normals for all edges by
  2355. calculating (-m,1) and unitizing it. These normals will not all
  2356. be oriented correctly.
  2357.  
  2358. Let x0, x1, x2, ..., xn-1 be the vertices in a clockwise or
  2359. counter-clockwise order around a n-sided polygon. Furthermore,
  2360. let Ni be the normal of the edge between xi and xi1.
  2361.  
  2362. The second step is finding the topmost vertex. In cases of
  2363. ambiguity, of all topmost vertices, take the leftmost. This
  2364. vertex is certain to be convex. Say this is vertex is vertex xi.
  2365.  
  2366. Let U be the vector from xi to xi1, and V be the vector from xi
  2367. to xi1. Then calculate the value of UNi. If it is positive,
  2368. invert Ni, otherwise do nothing. Similarly, calculate VNi1 and
  2369. if it is positive, invert Ni1, otherwise do nothing. Ni and Ni1
  2370. are now correctly oriented.
  2371.  
  2372. The point of that first step was to make at least one correctly
  2373. oriented normal. Then, start following the edges and generate
  2374. correctly oriented normals as follows.
  2375.  
  2376. Given a vertex xi for which Ni1 is known to be correctly
  2377. oriented, Ni can be computed as follows. Let U be the vector
  2378. from xi to xi1, and V be the vector from xi to xi1. Calculate
  2379. Ni1(U+V) and Ni(U+V). If the results are of the same sign do
  2380. nothing. If they are of different signs, invert Ni. Ni is now
  2381. correctly oriented.
  2382.  
  2383. Triangulating a polygon
  2384.  
  2385. Let us first cover the convex scenario. We will be using the
  2386. same notation as in the previous section.
  2387.  
  2388. Take any triplet of vertices xi1, xi, xi1. These three vertices
  2389. form the first triangle. Then, remove vertex xi from the list,
  2390. and the polygon has now one less vertex. Repeat until the
  2391. polygon is a triangle, at which point you are finished.
  2392.  
  2393. One step of the algorithm is shown above.
  2394.  
  2395. The concave scenario is a bit more complicated. What we will do
  2396. is split the concave polygon into smaller polygons, eventually
  2397. resulting in either triangles or convex polygons that can be
  2398. triangulated as above.
  2399.  
  2400. Find a vertex that is concave. Let U be the vector from xi1 to
  2401. xi. Then, vertex xi is concave if and only if UNi is more than
  2402. zero. Loop through the vertices until you find such a vertex. If
  2403. you do not find one, then the polygon is convex and triangulate
  2404. it as above.
  2405.  
  2406. From that vertex, find a second vertex xj for which the line
  2407. segment from xi to xj does not intersect any other edge. Then,
  2408. insert that new edge, making two polygons, one that has the
  2409. vertices xi, xi1, xi2, ..., xj, and one that has vertices xj,
  2410. xj1, xj2, ..., xi. Re-apply the algorithm on these two smaller
  2411. polygons.
  2412.  
  2413. It can be demonstrated that using the above algorithm on a n
  2414. sided polygon will generate exactly n-2 triangles.
  2415.  
  2416. Computing a plane normal from vertices
  2417.  
  2418. It can be shown that the (P,Q,R) components of the normal
  2419. vectors are proportional to the signed area of the projection of
  2420. the polygon on the yz, xz and xy plane respectively.
  2421.  
  2422. The signed area of a polygon in (u,v) coordinates can be shown
  2423. to be:
  2424.  
  2425. A(u,v)=1/20i<n(vi+vi1)(ui1-ui)
  2426.  
  2427. where (ui, vi) are the coordinates of vertex xi in 2d.
  2428.  
  2429. Since we're not really interested in the signed area, but some
  2430. constant time the signed area, the 1/2 can be safely ignored
  2431. without loss of precision.
  2432.  
  2433. Given a polygon in 3d, one can compute the above with:
  2434.  
  2435. P=A(y,z)    Q=A(z,x)    R=A(x,y)
  2436.  
  2437. Or, if you want, P is the area as calculated using only the y
  2438. and z components of the points in 3d, Q is the area as
  2439. calculated using the z and x components of points in 3d, and R
  2440. is the area as calculated using the x and y components of points
  2441. in 3d.
  2442.  
  2443. Once this value of (P,Q,R) is known, the result should be
  2444. normalized, and then correct orientation should be checked as
  2445. described hereafter.
  2446.  
  2447. It should be noted that the A(u,v) equation simplifies to
  2448.  
  2449. A(u,v)=1/2(u0-u1)(v0-v2)-(v0-v1)(u0-u3)
  2450.  
  2451. in the case of a triangle. Again, the 1/2 constant can be
  2452. ignored.
  2453.  
  2454. Generating correctly oriented normals for polyhedra
  2455.  
  2456. In some cases, normal orientation is implicit in the object
  2457. description we have. For instance, some modelers output all
  2458. vertices in a counterclockwise manner when seen from above. If
  2459. this is the case, then all that is needed is that the normal be
  2460. computed in a specific way, without changing the ordering of the
  2461. vertices. Then the normals will be correctly oriented.
  2462.  
  2463. If this is not the case, we need some form of algorithm to
  2464. ensure proper normal orientation.
  2465.  
  2466. For this task, we need to have computed the normals to the edges
  2467. to for all polygons making up the polyhedron, each in their
  2468. respective plane of course. The edges normals in the polygons
  2469. planes can be localized in space for the polyhedron, we are
  2470. going to use this. Note that each edge is connected to two
  2471. polygons, thus has two normals, one per polygon.
  2472.  
  2473. Find the vertex with the smallest x coordinate. In case of
  2474. ambiguity, resolve with the smallest y coordinate. In case of
  2475. ambiguity, resolve with the smallest z value. This vertex is
  2476. known to be convex. Take all edges connected to that vertex, and
  2477. find the vector U that is the sum of all edge normals (two per
  2478. edge). Then, for each face touching the point, calculate AU,
  2479. where A is the face normal. If the result is negative, invert A,
  2480. otherwise leave it as it is. All such faces now have correctly
  2481. oriented normal.
  2482.  
  2483. From this point, traverse all faces, propagating correctly
  2484. oriented normals as follows. Let us assume we have two faces F1
  2485. and F2, and that F1's normal is correctly oriented. Let A1 and
  2486. A2 denote F1 and F2's normals respectively. Pick an edge shared
  2487. by F1 and F2, and compute U, the sum of the two edge normals.
  2488. Then evaluate A1U and A2U. If they are of different signs,
  2489. invert A2, otherwise leave it that way. A2 is now correctly
  2490. oriented.
  2491.  
  2492. A special note, if the dot products are very close to zero, the
  2493. face should be initialized with the same normal, and marked as
  2494. ambiguous. Later, if you can find another face to help you
  2495. better determine the orientation of that face, use that normal
  2496. instead. At any rate, ambiguous faces should be avoided when
  2497. propagating normal orientation.
  2498.  
  2499. One very good way of propagating the normals is to start with
  2500. one of the initial faces for which we generated the normal, and
  2501. then do a depth first search through connected faces. The depth
  2502. first search is elementary and will not be discussed here
  2503. because it is not absolutely necessary, though it will tend to
  2504. minimize time spend computing normals orientation.
  2505.  
  2506. Polygon clipping against a line or plane
  2507.  
  2508. This problem often occurs in computer graphics, and is often
  2509. needed real time. Fortunately, convenient solutions exist that
  2510. work well.
  2511.  
  2512. The simplest solution is with convex polygons. In this case, one
  2513. should note that there are only 2 intersections of the clipping
  2514. line or plane with the edges of the polygon. When we face a
  2515. concave case, there is an even number of intersections with the
  2516. edges, but some ordering should be done for them, or degenerate
  2517. edges might result.
  2518.  
  2519. The method for clipping convex polygons is illustrated below.
  2520.  
  2521.  
  2522.  
  2523. Note that if one wants to keep both pieces of the clipped
  2524. polygon, this algorithm can be trivially extended.
  2525.  
  2526. A more formal way of describing this algorithm is as follows.
  2527.  
  2528.  
  2529.  
  2530. Let v1,v2,v3, ..., vn be the list of verticies, listed in a
  2531. clockwise or counter-clockwise fashion.
  2532.  
  2533.  
  2534.  
  2535. Then P1 will be the first piece of polygon, and P2 will be the
  2536. second piece.
  2537.  
  2538.  
  2539.  
  2540. For i iterating from 1 to n do
  2541.  
  2542. If the edge from vi to vi1 intersects the clipping line
  2543.  
  2544.     break loop
  2545.  
  2546. End if
  2547.  
  2548. End for
  2549.  
  2550.  
  2551.  
  2552. For j iterating from i to n do
  2553.  
  2554. If the edge from vj to vj1 intersects the clipping line
  2555.  
  2556.     break loop
  2557.  
  2558. End if
  2559.  
  2560. End for
  2561.  
  2562.  
  2563.  
  2564. Let x be the intersection point of edge vi-vi1 with the clipping
  2565. line.
  2566.  
  2567. Let y be the intersection point of edge vj-vj1 with the clipping
  2568. line.
  2569.  
  2570.  
  2571.  
  2572. P1 is (in clockwise or counterclockwise)
  2573.  
  2574.     v1,v2, ..., vi, x, y, vj+1, vj+1, ..., vn
  2575.  
  2576. P2 is x,vi+1,vi+2, ..., vj,y
  2577.  
  2578. When doing this to a concave polygon, the algorithm is slightly
  2579. more complex. Find all intersection points of edges with
  2580. clipping line, and sort them according to some arbitrary axis
  2581. (try to use one for which the points coordinates vary a bit).
  2582. Name these sorted points p1, p2, ..., pn. Then, insert the new
  2583. edges p1-p2, p3-p4, ..., pn-1 - pn. Then separate the two
  2584. polygons and you are done.
  2585.  
  2586. Glossary
  2587.  
  2588. Convex: term used to describe polytopes, such as polygons and
  2589. polyhedra. It means that the inside angle is always less than or
  2590. equal to 180. A triangle is always convex. A square or a
  2591. rectangle is convex, but other quadrilaterals may not be convex.
  2592. The term convex is sometimes used for a vertex or edge to say
  2593. that the inside angle at the vertex or edge is less than or
  2594. equal to 180. An equivalent definition of convexity is, given a
  2595. polytope, the intersection of the polytope and any line is
  2596. always 0 or 2 points except in degenerate cases.
  2597.  
  2598. Concave: any polytope that is not convex is concave.
  2599.  
  2600. Edge: a line segment between 2 vertices. An edge typically
  2601. delimitates a polygon. A square has 4 edges, a cube has 12.
  2602.  
  2603. Face: a polygon that delimitates a polyhedron. A face is always
  2604. planar. A cube has 6 faces. Also, since polygons in 3d have two
  2605. sides, these are sometimes referred to as faces.
  2606.  
  2607. Matrix: a 2 dimensional array of real numbers. Can also be
  2608. thought as an array of vectors, or a vector of vectors.
  2609.  
  2610. Polygon: a flat, 2d polytope delimited by straight edges and
  2611. vertices. Examples include triangles, squares, decagons. We
  2612. normally prefer all vertices to be distinct, and that edges do
  2613. not cross. We don't like it either when the polygon is
  2614. disconnected (e.g. has several, distinct parts that are not
  2615. connected).
  2616.  
  2617. Polyhedron: a 3d polytope delimited by planar faces, linear
  2618. edges and vertices. Examples include cubes, tetrahedra,
  2619. icosahedra. As with the polygon, we prefer vertices to be
  2620. distinct, edges not to cross, faces not to intersect, and the
  2621. polyhedron to be made of one piece as opposed to several
  2622. disconnected pieces.
  2623.  
  2624. Polynomial: a mathematical entity that can be reduced to the
  2625. form a0+a1x+a2x2+a3x3+...+anxn for some n, ai being a real
  2626. number and xi a real variable. Example polynomials include: 3,
  2627. 2+x, x5+2x+3, x(x+2)(x-3). Examples of things that are not
  2628. polynomials: x(x+1)/(x+2), x2+x+sinx.
  2629.  
  2630. Polytope: an object in n dimensions defined by linear
  2631. constraints. Examples in 2d and 3d are polygons and polyhedra,
  2632. respectively. Polytopes are made of a single piece. That is,
  2633. from any point in a polytope, there is a path (which might be
  2634. twisted) that can get you to any other point in the polytope
  2635. without exiting the polytope.
  2636.  
  2637. Taylor series: A power series that approximates a function.
  2638.  
  2639. Vector: strictly speaking, a n-uplet, such as (3,2,5,1). It can
  2640. be viewed as an arrow in any number of dimensions, from one
  2641. point p1 to a point p2. The vector from (x,y,z) to (a,b,c) is
  2642. (a-x,b-y,c-z).
  2643.  
  2644. Vertex: a point, usually called this way when it is the endpoint
  2645. of at least one edge. A square has 4 vertices, a cube has 8.
  2646.  
  2647.